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.

20537 lines
794 KiB

2 months ago
  1. import { _registerComponent, registerVersion, _getProvider, getApp, _removeServiceInstance, SDK_VERSION } from '@firebase/app';
  2. import { Component } from '@firebase/component';
  3. import { Logger, LogLevel } from '@firebase/logger';
  4. import { FirebaseError, createMockUserToken, getModularInstance, deepEqual, getDefaultEmulatorHostnameAndPort, getUA, isIndexedDBAvailable, isSafari } from '@firebase/util';
  5. import { XhrIo, EventType, ErrorCode, createWebChannelTransport, getStatEventTarget, FetchXmlHttpFactory, WebChannel, Event, Stat } from '@firebase/webchannel-wrapper';
  6. const b = "@firebase/firestore";
  7. /**
  8. * @license
  9. * Copyright 2017 Google LLC
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. /**
  24. * Simple wrapper around a nullable UID. Mostly exists to make code more
  25. * readable.
  26. */
  27. class P {
  28. constructor(t) {
  29. this.uid = t;
  30. }
  31. isAuthenticated() {
  32. return null != this.uid;
  33. }
  34. /**
  35. * Returns a key representing this user, suitable for inclusion in a
  36. * dictionary.
  37. */ toKey() {
  38. return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
  39. }
  40. isEqual(t) {
  41. return t.uid === this.uid;
  42. }
  43. }
  44. /** A user with a null UID. */ P.UNAUTHENTICATED = new P(null),
  45. // TODO(mikelehen): Look into getting a proper uid-equivalent for
  46. // non-FirebaseAuth providers.
  47. P.GOOGLE_CREDENTIALS = new P("google-credentials-uid"), P.FIRST_PARTY = new P("first-party-uid"),
  48. P.MOCK_USER = new P("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. let v = "9.16.0";
  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. const V = new Logger("@firebase/firestore");
  83. // Helper methods are needed because variables can't be exported as read/write
  84. function S() {
  85. return V.logLevel;
  86. }
  87. /**
  88. * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
  89. *
  90. * @param logLevel - The verbosity you set for activity and error logging. Can
  91. * be any of the following values:
  92. *
  93. * <ul>
  94. * <li>`debug` for the most verbose logging level, primarily for
  95. * debugging.</li>
  96. * <li>`error` to log errors only.</li>
  97. * <li><code>`silent` to turn off logging.</li>
  98. * </ul>
  99. */ function D(t) {
  100. V.setLogLevel(t);
  101. }
  102. function C(t, ...e) {
  103. if (V.logLevel <= LogLevel.DEBUG) {
  104. const n = e.map(k);
  105. V.debug(`Firestore (${v}): ${t}`, ...n);
  106. }
  107. }
  108. function x(t, ...e) {
  109. if (V.logLevel <= LogLevel.ERROR) {
  110. const n = e.map(k);
  111. V.error(`Firestore (${v}): ${t}`, ...n);
  112. }
  113. }
  114. /**
  115. * @internal
  116. */ function N(t, ...e) {
  117. if (V.logLevel <= LogLevel.WARN) {
  118. const n = e.map(k);
  119. V.warn(`Firestore (${v}): ${t}`, ...n);
  120. }
  121. }
  122. /**
  123. * Converts an additional log parameter to a string representation.
  124. */ function k(t) {
  125. if ("string" == typeof t) return t;
  126. try {
  127. return e = t, JSON.stringify(e);
  128. } catch (e) {
  129. // Converting to JSON failed, just log the object directly
  130. return t;
  131. }
  132. /**
  133. * @license
  134. * Copyright 2020 Google LLC
  135. *
  136. * Licensed under the Apache License, Version 2.0 (the "License");
  137. * you may not use this file except in compliance with the License.
  138. * You may obtain a copy of the License at
  139. *
  140. * http://www.apache.org/licenses/LICENSE-2.0
  141. *
  142. * Unless required by applicable law or agreed to in writing, software
  143. * distributed under the License is distributed on an "AS IS" BASIS,
  144. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  145. * See the License for the specific language governing permissions and
  146. * limitations under the License.
  147. */
  148. /** Formats an object as a JSON string, suitable for logging. */
  149. var e;
  150. }
  151. /**
  152. * @license
  153. * Copyright 2017 Google LLC
  154. *
  155. * Licensed under the Apache License, Version 2.0 (the "License");
  156. * you may not use this file except in compliance with the License.
  157. * You may obtain a copy of the License at
  158. *
  159. * http://www.apache.org/licenses/LICENSE-2.0
  160. *
  161. * Unless required by applicable law or agreed to in writing, software
  162. * distributed under the License is distributed on an "AS IS" BASIS,
  163. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  164. * See the License for the specific language governing permissions and
  165. * limitations under the License.
  166. */
  167. /**
  168. * Unconditionally fails, throwing an Error with the given message.
  169. * Messages are stripped in production builds.
  170. *
  171. * Returns `never` and can be used in expressions:
  172. * @example
  173. * let futureVar = fail('not implemented yet');
  174. */ function O(t = "Unexpected state") {
  175. // Log the failure in addition to throw an exception, just in case the
  176. // exception is swallowed.
  177. const e = `FIRESTORE (${v}) INTERNAL ASSERTION FAILED: ` + t;
  178. // NOTE: We don't use FirestoreError here because these are internal failures
  179. // that cannot be handled by the user. (Also it would create a circular
  180. // dependency between the error and assert modules which doesn't work.)
  181. throw x(e), new Error(e);
  182. }
  183. /**
  184. * Fails if the given assertion condition is false, throwing an Error with the
  185. * given message if it did.
  186. *
  187. * Messages are stripped in production builds.
  188. */ function M(t, e) {
  189. t || O();
  190. }
  191. /**
  192. * Fails if the given assertion condition is false, throwing an Error with the
  193. * given message if it did.
  194. *
  195. * The code of callsites invoking this function are stripped out in production
  196. * builds. Any side-effects of code within the debugAssert() invocation will not
  197. * happen in this case.
  198. *
  199. * @internal
  200. */ function F(t, e) {
  201. t || O();
  202. }
  203. /**
  204. * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
  205. * instance of `T` before casting.
  206. */ function $(t,
  207. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  208. e) {
  209. return t;
  210. }
  211. /**
  212. * @license
  213. * Copyright 2017 Google LLC
  214. *
  215. * Licensed under the Apache License, Version 2.0 (the "License");
  216. * you may not use this file except in compliance with the License.
  217. * You may obtain a copy of the License at
  218. *
  219. * http://www.apache.org/licenses/LICENSE-2.0
  220. *
  221. * Unless required by applicable law or agreed to in writing, software
  222. * distributed under the License is distributed on an "AS IS" BASIS,
  223. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  224. * See the License for the specific language governing permissions and
  225. * limitations under the License.
  226. */ const B = {
  227. // Causes are copied from:
  228. // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  229. /** Not an error; returned on success. */
  230. OK: "ok",
  231. /** The operation was cancelled (typically by the caller). */
  232. CANCELLED: "cancelled",
  233. /** Unknown error or an error from a different error domain. */
  234. UNKNOWN: "unknown",
  235. /**
  236. * Client specified an invalid argument. Note that this differs from
  237. * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
  238. * problematic regardless of the state of the system (e.g., a malformed file
  239. * name).
  240. */
  241. INVALID_ARGUMENT: "invalid-argument",
  242. /**
  243. * Deadline expired before operation could complete. For operations that
  244. * change the state of the system, this error may be returned even if the
  245. * operation has completed successfully. For example, a successful response
  246. * from a server could have been delayed long enough for the deadline to
  247. * expire.
  248. */
  249. DEADLINE_EXCEEDED: "deadline-exceeded",
  250. /** Some requested entity (e.g., file or directory) was not found. */
  251. NOT_FOUND: "not-found",
  252. /**
  253. * Some entity that we attempted to create (e.g., file or directory) already
  254. * exists.
  255. */
  256. ALREADY_EXISTS: "already-exists",
  257. /**
  258. * The caller does not have permission to execute the specified operation.
  259. * PERMISSION_DENIED must not be used for rejections caused by exhausting
  260. * some resource (use RESOURCE_EXHAUSTED instead for those errors).
  261. * PERMISSION_DENIED must not be used if the caller can not be identified
  262. * (use UNAUTHENTICATED instead for those errors).
  263. */
  264. PERMISSION_DENIED: "permission-denied",
  265. /**
  266. * The request does not have valid authentication credentials for the
  267. * operation.
  268. */
  269. UNAUTHENTICATED: "unauthenticated",
  270. /**
  271. * Some resource has been exhausted, perhaps a per-user quota, or perhaps the
  272. * entire file system is out of space.
  273. */
  274. RESOURCE_EXHAUSTED: "resource-exhausted",
  275. /**
  276. * Operation was rejected because the system is not in a state required for
  277. * the operation's execution. For example, directory to be deleted may be
  278. * non-empty, an rmdir operation is applied to a non-directory, etc.
  279. *
  280. * A litmus test that may help a service implementor in deciding
  281. * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
  282. * (a) Use UNAVAILABLE if the client can retry just the failing call.
  283. * (b) Use ABORTED if the client should retry at a higher-level
  284. * (e.g., restarting a read-modify-write sequence).
  285. * (c) Use FAILED_PRECONDITION if the client should not retry until
  286. * the system state has been explicitly fixed. E.g., if an "rmdir"
  287. * fails because the directory is non-empty, FAILED_PRECONDITION
  288. * should be returned since the client should not retry unless
  289. * they have first fixed up the directory by deleting files from it.
  290. * (d) Use FAILED_PRECONDITION if the client performs conditional
  291. * REST Get/Update/Delete on a resource and the resource on the
  292. * server does not match the condition. E.g., conflicting
  293. * read-modify-write on the same resource.
  294. */
  295. FAILED_PRECONDITION: "failed-precondition",
  296. /**
  297. * The operation was aborted, typically due to a concurrency issue like
  298. * sequencer check failures, transaction aborts, etc.
  299. *
  300. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  301. * and UNAVAILABLE.
  302. */
  303. ABORTED: "aborted",
  304. /**
  305. * Operation was attempted past the valid range. E.g., seeking or reading
  306. * past end of file.
  307. *
  308. * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
  309. * if the system state changes. For example, a 32-bit file system will
  310. * generate INVALID_ARGUMENT if asked to read at an offset that is not in the
  311. * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
  312. * an offset past the current file size.
  313. *
  314. * There is a fair bit of overlap between FAILED_PRECONDITION and
  315. * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
  316. * when it applies so that callers who are iterating through a space can
  317. * easily look for an OUT_OF_RANGE error to detect when they are done.
  318. */
  319. OUT_OF_RANGE: "out-of-range",
  320. /** Operation is not implemented or not supported/enabled in this service. */
  321. UNIMPLEMENTED: "unimplemented",
  322. /**
  323. * Internal errors. Means some invariants expected by underlying System has
  324. * been broken. If you see one of these errors, Something is very broken.
  325. */
  326. INTERNAL: "internal",
  327. /**
  328. * The service is currently unavailable. This is a most likely a transient
  329. * condition and may be corrected by retrying with a backoff.
  330. *
  331. * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
  332. * and UNAVAILABLE.
  333. */
  334. UNAVAILABLE: "unavailable",
  335. /** Unrecoverable data loss or corruption. */
  336. DATA_LOSS: "data-loss"
  337. };
  338. /** An error returned by a Firestore operation. */ class L extends FirebaseError {
  339. /** @hideconstructor */
  340. constructor(
  341. /**
  342. * The backend error code associated with this error.
  343. */
  344. t,
  345. /**
  346. * A custom error description.
  347. */
  348. e) {
  349. super(t, e), this.code = t, this.message = e,
  350. // HACK: We write a toString property directly because Error is not a real
  351. // class and so inheritance does not work correctly. We could alternatively
  352. // do the same "back-door inheritance" trick that FirebaseError does.
  353. this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
  354. }
  355. }
  356. /**
  357. * @license
  358. * Copyright 2017 Google LLC
  359. *
  360. * Licensed under the Apache License, Version 2.0 (the "License");
  361. * you may not use this file except in compliance with the License.
  362. * You may obtain a copy of the License at
  363. *
  364. * http://www.apache.org/licenses/LICENSE-2.0
  365. *
  366. * Unless required by applicable law or agreed to in writing, software
  367. * distributed under the License is distributed on an "AS IS" BASIS,
  368. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  369. * See the License for the specific language governing permissions and
  370. * limitations under the License.
  371. */ class q {
  372. constructor() {
  373. this.promise = new Promise(((t, e) => {
  374. this.resolve = t, this.reject = e;
  375. }));
  376. }
  377. }
  378. /**
  379. * @license
  380. * Copyright 2017 Google LLC
  381. *
  382. * Licensed under the Apache License, Version 2.0 (the "License");
  383. * you may not use this file except in compliance with the License.
  384. * You may obtain a copy of the License at
  385. *
  386. * http://www.apache.org/licenses/LICENSE-2.0
  387. *
  388. * Unless required by applicable law or agreed to in writing, software
  389. * distributed under the License is distributed on an "AS IS" BASIS,
  390. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  391. * See the License for the specific language governing permissions and
  392. * limitations under the License.
  393. */ class U {
  394. constructor(t, e) {
  395. this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${t}`);
  396. }
  397. }
  398. /**
  399. * A CredentialsProvider that always yields an empty token.
  400. * @internal
  401. */ class K {
  402. getToken() {
  403. return Promise.resolve(null);
  404. }
  405. invalidateToken() {}
  406. start(t, e) {
  407. // Fire with initial user.
  408. t.enqueueRetryable((() => e(P.UNAUTHENTICATED)));
  409. }
  410. shutdown() {}
  411. }
  412. /**
  413. * A CredentialsProvider that always returns a constant token. Used for
  414. * emulator token mocking.
  415. */ class G {
  416. constructor(t) {
  417. this.token = t,
  418. /**
  419. * Stores the listener registered with setChangeListener()
  420. * This isn't actually necessary since the UID never changes, but we use this
  421. * to verify the listen contract is adhered to in tests.
  422. */
  423. this.changeListener = null;
  424. }
  425. getToken() {
  426. return Promise.resolve(this.token);
  427. }
  428. invalidateToken() {}
  429. start(t, e) {
  430. this.changeListener = e,
  431. // Fire with initial user.
  432. t.enqueueRetryable((() => e(this.token.user)));
  433. }
  434. shutdown() {
  435. this.changeListener = null;
  436. }
  437. }
  438. class Q {
  439. constructor(t) {
  440. this.t = t,
  441. /** Tracks the current User. */
  442. this.currentUser = P.UNAUTHENTICATED,
  443. /**
  444. * Counter used to detect if the token changed while a getToken request was
  445. * outstanding.
  446. */
  447. this.i = 0, this.forceRefresh = !1, this.auth = null;
  448. }
  449. start(t, e) {
  450. let n = this.i;
  451. // A change listener that prevents double-firing for the same token change.
  452. const s = t => this.i !== n ? (n = this.i, e(t)) : Promise.resolve();
  453. // A promise that can be waited on to block on the next token change.
  454. // This promise is re-created after each change.
  455. let i = new q;
  456. this.o = () => {
  457. this.i++, this.currentUser = this.u(), i.resolve(), i = new q, t.enqueueRetryable((() => s(this.currentUser)));
  458. };
  459. const r = () => {
  460. const e = i;
  461. t.enqueueRetryable((async () => {
  462. await e.promise, await s(this.currentUser);
  463. }));
  464. }, o = t => {
  465. C("FirebaseAuthCredentialsProvider", "Auth detected"), this.auth = t, this.auth.addAuthTokenListener(this.o),
  466. r();
  467. };
  468. this.t.onInit((t => o(t))),
  469. // Our users can initialize Auth right after Firestore, so we give it
  470. // a chance to register itself with the component framework before we
  471. // determine whether to start up in unauthenticated mode.
  472. setTimeout((() => {
  473. if (!this.auth) {
  474. const t = this.t.getImmediate({
  475. optional: !0
  476. });
  477. t ? o(t) : (
  478. // If auth is still not available, proceed with `null` user
  479. C("FirebaseAuthCredentialsProvider", "Auth not yet detected"), i.resolve(), i = new q);
  480. }
  481. }), 0), r();
  482. }
  483. getToken() {
  484. // Take note of the current value of the tokenCounter so that this method
  485. // can fail (with an ABORTED error) if there is a token change while the
  486. // request is outstanding.
  487. const t = this.i, e = this.forceRefresh;
  488. return this.forceRefresh = !1, this.auth ? this.auth.getToken(e).then((e =>
  489. // Cancel the request since the token changed while the request was
  490. // outstanding so the response is potentially for a previous user (which
  491. // user, we can't be sure).
  492. this.i !== t ? (C("FirebaseAuthCredentialsProvider", "getToken aborted due to token change."),
  493. this.getToken()) : e ? (M("string" == typeof e.accessToken), new U(e.accessToken, this.currentUser)) : null)) : Promise.resolve(null);
  494. }
  495. invalidateToken() {
  496. this.forceRefresh = !0;
  497. }
  498. shutdown() {
  499. this.auth && this.auth.removeAuthTokenListener(this.o);
  500. }
  501. // Auth.getUid() can return null even with a user logged in. It is because
  502. // getUid() is synchronous, but the auth code populating Uid is asynchronous.
  503. // This method should only be called in the AuthTokenListener callback
  504. // to guarantee to get the actual user.
  505. u() {
  506. const t = this.auth && this.auth.getUid();
  507. return M(null === t || "string" == typeof t), new P(t);
  508. }
  509. }
  510. /*
  511. * FirstPartyToken provides a fresh token each time its value
  512. * is requested, because if the token is too old, requests will be rejected.
  513. * Technically this may no longer be necessary since the SDK should gracefully
  514. * recover from unauthenticated errors (see b/33147818 for context), but it's
  515. * safer to keep the implementation as-is.
  516. */ class j {
  517. constructor(t, e, n, s) {
  518. this.h = t, this.l = e, this.m = n, this.g = s, this.type = "FirstParty", this.user = P.FIRST_PARTY,
  519. this.p = new Map;
  520. }
  521. /** Gets an authorization token, using a provided factory function, or falling back to First Party GAPI. */ I() {
  522. return this.g ? this.g() : (
  523. // Make sure this really is a Gapi client.
  524. M(!("object" != typeof this.h || null === this.h || !this.h.auth || !this.h.auth.getAuthHeaderValueForFirstParty)),
  525. this.h.auth.getAuthHeaderValueForFirstParty([]));
  526. }
  527. get headers() {
  528. this.p.set("X-Goog-AuthUser", this.l);
  529. // Use array notation to prevent minification
  530. const t = this.I();
  531. return t && this.p.set("Authorization", t), this.m && this.p.set("X-Goog-Iam-Authorization-Token", this.m),
  532. this.p;
  533. }
  534. }
  535. /*
  536. * Provides user credentials required for the Firestore JavaScript SDK
  537. * to authenticate the user, using technique that is only available
  538. * to applications hosted by Google.
  539. */ class W {
  540. constructor(t, e, n, s) {
  541. this.h = t, this.l = e, this.m = n, this.g = s;
  542. }
  543. getToken() {
  544. return Promise.resolve(new j(this.h, this.l, this.m, this.g));
  545. }
  546. start(t, e) {
  547. // Fire with initial uid.
  548. t.enqueueRetryable((() => e(P.FIRST_PARTY)));
  549. }
  550. shutdown() {}
  551. invalidateToken() {}
  552. }
  553. class z {
  554. constructor(t) {
  555. this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value);
  556. }
  557. }
  558. class H {
  559. constructor(t) {
  560. this.T = t, this.forceRefresh = !1, this.appCheck = null, this.A = null;
  561. }
  562. start(t, e) {
  563. const n = t => {
  564. null != t.error && C("FirebaseAppCheckTokenProvider", `Error getting App Check token; using placeholder token instead. Error: ${t.error.message}`);
  565. const n = t.token !== this.A;
  566. return this.A = t.token, C("FirebaseAppCheckTokenProvider", `Received ${n ? "new" : "existing"} token.`),
  567. n ? e(t.token) : Promise.resolve();
  568. };
  569. this.o = e => {
  570. t.enqueueRetryable((() => n(e)));
  571. };
  572. const s = t => {
  573. C("FirebaseAppCheckTokenProvider", "AppCheck detected"), this.appCheck = t, this.appCheck.addTokenListener(this.o);
  574. };
  575. this.T.onInit((t => s(t))),
  576. // Our users can initialize AppCheck after Firestore, so we give it
  577. // a chance to register itself with the component framework.
  578. setTimeout((() => {
  579. if (!this.appCheck) {
  580. const t = this.T.getImmediate({
  581. optional: !0
  582. });
  583. t ? s(t) :
  584. // If AppCheck is still not available, proceed without it.
  585. C("FirebaseAppCheckTokenProvider", "AppCheck not yet detected");
  586. }
  587. }), 0);
  588. }
  589. getToken() {
  590. const t = this.forceRefresh;
  591. return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(t).then((t => t ? (M("string" == typeof t.token),
  592. this.A = t.token, new z(t.token)) : null)) : Promise.resolve(null);
  593. }
  594. invalidateToken() {
  595. this.forceRefresh = !0;
  596. }
  597. shutdown() {
  598. this.appCheck && this.appCheck.removeTokenListener(this.o);
  599. }
  600. }
  601. /**
  602. * An AppCheck token provider that always yields an empty token.
  603. * @internal
  604. */ class J {
  605. getToken() {
  606. return Promise.resolve(new z(""));
  607. }
  608. invalidateToken() {}
  609. start(t, e) {}
  610. shutdown() {}
  611. }
  612. /**
  613. * Builds a CredentialsProvider depending on the type of
  614. * the credentials passed in.
  615. */
  616. /**
  617. * @license
  618. * Copyright 2020 Google LLC
  619. *
  620. * Licensed under the Apache License, Version 2.0 (the "License");
  621. * you may not use this file except in compliance with the License.
  622. * You may obtain a copy of the License at
  623. *
  624. * http://www.apache.org/licenses/LICENSE-2.0
  625. *
  626. * Unless required by applicable law or agreed to in writing, software
  627. * distributed under the License is distributed on an "AS IS" BASIS,
  628. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  629. * See the License for the specific language governing permissions and
  630. * limitations under the License.
  631. */
  632. /**
  633. * Generates `nBytes` of random bytes.
  634. *
  635. * If `nBytes < 0` , an error will be thrown.
  636. */
  637. function Y(t) {
  638. // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.
  639. const e =
  640. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  641. "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);
  642. if (e && "function" == typeof e.getRandomValues) e.getRandomValues(n); else
  643. // Falls back to Math.random
  644. for (let e = 0; e < t; e++) n[e] = Math.floor(256 * Math.random());
  645. return n;
  646. }
  647. /**
  648. * @license
  649. * Copyright 2017 Google LLC
  650. *
  651. * Licensed under the Apache License, Version 2.0 (the "License");
  652. * you may not use this file except in compliance with the License.
  653. * You may obtain a copy of the License at
  654. *
  655. * http://www.apache.org/licenses/LICENSE-2.0
  656. *
  657. * Unless required by applicable law or agreed to in writing, software
  658. * distributed under the License is distributed on an "AS IS" BASIS,
  659. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  660. * See the License for the specific language governing permissions and
  661. * limitations under the License.
  662. */ class X {
  663. static R() {
  664. // Alphanumeric characters
  665. const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length;
  666. // The largest byte value that is a multiple of `char.length`.
  667. let n = "";
  668. for (;n.length < 20; ) {
  669. const s = Y(40);
  670. for (let i = 0; i < s.length; ++i)
  671. // Only accept values that are [0, maxMultiple), this ensures they can
  672. // be evenly mapped to indices of `chars` via a modulo operation.
  673. n.length < 20 && s[i] < e && (n += t.charAt(s[i] % t.length));
  674. }
  675. return n;
  676. }
  677. }
  678. function Z(t, e) {
  679. return t < e ? -1 : t > e ? 1 : 0;
  680. }
  681. /** Helper to compare arrays using isEqual(). */ function tt(t, e, n) {
  682. return t.length === e.length && t.every(((t, s) => n(t, e[s])));
  683. }
  684. /**
  685. * Returns the immediate lexicographically-following string. This is useful to
  686. * construct an inclusive range for indexeddb iterators.
  687. */ function et(t) {
  688. // Return the input string, with an additional NUL byte appended.
  689. return t + "\0";
  690. }
  691. /**
  692. * @license
  693. * Copyright 2017 Google LLC
  694. *
  695. * Licensed under the Apache License, Version 2.0 (the "License");
  696. * you may not use this file except in compliance with the License.
  697. * You may obtain a copy of the License at
  698. *
  699. * http://www.apache.org/licenses/LICENSE-2.0
  700. *
  701. * Unless required by applicable law or agreed to in writing, software
  702. * distributed under the License is distributed on an "AS IS" BASIS,
  703. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  704. * See the License for the specific language governing permissions and
  705. * limitations under the License.
  706. */
  707. // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
  708. /**
  709. * A `Timestamp` represents a point in time independent of any time zone or
  710. * calendar, represented as seconds and fractions of seconds at nanosecond
  711. * resolution in UTC Epoch time.
  712. *
  713. * It is encoded using the Proleptic Gregorian Calendar which extends the
  714. * Gregorian calendar backwards to year one. It is encoded assuming all minutes
  715. * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
  716. * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
  717. * 9999-12-31T23:59:59.999999999Z.
  718. *
  719. * For examples and further specifications, refer to the
  720. * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
  721. */
  722. class nt {
  723. /**
  724. * Creates a new timestamp.
  725. *
  726. * @param seconds - The number of seconds of UTC time since Unix epoch
  727. * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  728. * 9999-12-31T23:59:59Z inclusive.
  729. * @param nanoseconds - The non-negative fractions of a second at nanosecond
  730. * resolution. Negative second values with fractions must still have
  731. * non-negative nanoseconds values that count forward in time. Must be
  732. * from 0 to 999,999,999 inclusive.
  733. */
  734. constructor(
  735. /**
  736. * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
  737. */
  738. t,
  739. /**
  740. * The fractions of a second at nanosecond resolution.*
  741. */
  742. e) {
  743. if (this.seconds = t, this.nanoseconds = e, e < 0) throw new L(B.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
  744. if (e >= 1e9) throw new L(B.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
  745. if (t < -62135596800) throw new L(B.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
  746. // This will break in the year 10,000.
  747. if (t >= 253402300800) throw new L(B.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
  748. }
  749. /**
  750. * Creates a new timestamp with the current date, with millisecond precision.
  751. *
  752. * @returns a new timestamp representing the current date.
  753. */ static now() {
  754. return nt.fromMillis(Date.now());
  755. }
  756. /**
  757. * Creates a new timestamp from the given date.
  758. *
  759. * @param date - The date to initialize the `Timestamp` from.
  760. * @returns A new `Timestamp` representing the same point in time as the given
  761. * date.
  762. */ static fromDate(t) {
  763. return nt.fromMillis(t.getTime());
  764. }
  765. /**
  766. * Creates a new timestamp from the given number of milliseconds.
  767. *
  768. * @param milliseconds - Number of milliseconds since Unix epoch
  769. * 1970-01-01T00:00:00Z.
  770. * @returns A new `Timestamp` representing the same point in time as the given
  771. * number of milliseconds.
  772. */ static fromMillis(t) {
  773. const e = Math.floor(t / 1e3), n = Math.floor(1e6 * (t - 1e3 * e));
  774. return new nt(e, n);
  775. }
  776. /**
  777. * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
  778. * causes a loss of precision since `Date` objects only support millisecond
  779. * precision.
  780. *
  781. * @returns JavaScript `Date` object representing the same point in time as
  782. * this `Timestamp`, with millisecond precision.
  783. */ toDate() {
  784. return new Date(this.toMillis());
  785. }
  786. /**
  787. * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
  788. * epoch). This operation causes a loss of precision.
  789. *
  790. * @returns The point in time corresponding to this timestamp, represented as
  791. * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
  792. */ toMillis() {
  793. return 1e3 * this.seconds + this.nanoseconds / 1e6;
  794. }
  795. _compareTo(t) {
  796. return this.seconds === t.seconds ? Z(this.nanoseconds, t.nanoseconds) : Z(this.seconds, t.seconds);
  797. }
  798. /**
  799. * Returns true if this `Timestamp` is equal to the provided one.
  800. *
  801. * @param other - The `Timestamp` to compare against.
  802. * @returns true if this `Timestamp` is equal to the provided one.
  803. */ isEqual(t) {
  804. return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;
  805. }
  806. /** Returns a textual representation of this `Timestamp`. */ toString() {
  807. return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
  808. }
  809. /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() {
  810. return {
  811. seconds: this.seconds,
  812. nanoseconds: this.nanoseconds
  813. };
  814. }
  815. /**
  816. * Converts this object to a primitive string, which allows `Timestamp` objects
  817. * to be compared using the `>`, `<=`, `>=` and `>` operators.
  818. */ valueOf() {
  819. // This method returns a string of the form <seconds>.<nanoseconds> where
  820. // <seconds> is translated to have a non-negative value and both <seconds>
  821. // and <nanoseconds> are left-padded with zeroes to be a consistent length.
  822. // Strings with this format then have a lexiographical ordering that matches
  823. // the expected ordering. The <seconds> translation is done to avoid having
  824. // a leading negative sign (i.e. a leading '-' character) in its string
  825. // representation, which would affect its lexiographical ordering.
  826. const t = this.seconds - -62135596800;
  827. // Note: Up to 12 decimal digits are required to represent all valid
  828. // 'seconds' values.
  829. return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0");
  830. }
  831. }
  832. /**
  833. * @license
  834. * Copyright 2017 Google LLC
  835. *
  836. * Licensed under the Apache License, Version 2.0 (the "License");
  837. * you may not use this file except in compliance with the License.
  838. * You may obtain a copy of the License at
  839. *
  840. * http://www.apache.org/licenses/LICENSE-2.0
  841. *
  842. * Unless required by applicable law or agreed to in writing, software
  843. * distributed under the License is distributed on an "AS IS" BASIS,
  844. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  845. * See the License for the specific language governing permissions and
  846. * limitations under the License.
  847. */
  848. /**
  849. * A version of a document in Firestore. This corresponds to the version
  850. * timestamp, such as update_time or read_time.
  851. */ class st {
  852. constructor(t) {
  853. this.timestamp = t;
  854. }
  855. static fromTimestamp(t) {
  856. return new st(t);
  857. }
  858. static min() {
  859. return new st(new nt(0, 0));
  860. }
  861. static max() {
  862. return new st(new nt(253402300799, 999999999));
  863. }
  864. compareTo(t) {
  865. return this.timestamp._compareTo(t.timestamp);
  866. }
  867. isEqual(t) {
  868. return this.timestamp.isEqual(t.timestamp);
  869. }
  870. /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() {
  871. // Convert to microseconds.
  872. return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
  873. }
  874. toString() {
  875. return "SnapshotVersion(" + this.timestamp.toString() + ")";
  876. }
  877. toTimestamp() {
  878. return this.timestamp;
  879. }
  880. }
  881. /**
  882. * @license
  883. * Copyright 2017 Google LLC
  884. *
  885. * Licensed under the Apache License, Version 2.0 (the "License");
  886. * you may not use this file except in compliance with the License.
  887. * You may obtain a copy of the License at
  888. *
  889. * http://www.apache.org/licenses/LICENSE-2.0
  890. *
  891. * Unless required by applicable law or agreed to in writing, software
  892. * distributed under the License is distributed on an "AS IS" BASIS,
  893. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  894. * See the License for the specific language governing permissions and
  895. * limitations under the License.
  896. */
  897. /**
  898. * Path represents an ordered sequence of string segments.
  899. */
  900. class it {
  901. constructor(t, e, n) {
  902. void 0 === e ? e = 0 : e > t.length && O(), void 0 === n ? n = t.length - e : n > t.length - e && O(),
  903. this.segments = t, this.offset = e, this.len = n;
  904. }
  905. get length() {
  906. return this.len;
  907. }
  908. isEqual(t) {
  909. return 0 === it.comparator(this, t);
  910. }
  911. child(t) {
  912. const e = this.segments.slice(this.offset, this.limit());
  913. return t instanceof it ? t.forEach((t => {
  914. e.push(t);
  915. })) : e.push(t), this.construct(e);
  916. }
  917. /** The index of one past the last segment of the path. */ limit() {
  918. return this.offset + this.length;
  919. }
  920. popFirst(t) {
  921. return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);
  922. }
  923. popLast() {
  924. return this.construct(this.segments, this.offset, this.length - 1);
  925. }
  926. firstSegment() {
  927. return this.segments[this.offset];
  928. }
  929. lastSegment() {
  930. return this.get(this.length - 1);
  931. }
  932. get(t) {
  933. return this.segments[this.offset + t];
  934. }
  935. isEmpty() {
  936. return 0 === this.length;
  937. }
  938. isPrefixOf(t) {
  939. if (t.length < this.length) return !1;
  940. for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  941. return !0;
  942. }
  943. isImmediateParentOf(t) {
  944. if (this.length + 1 !== t.length) return !1;
  945. for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
  946. return !0;
  947. }
  948. forEach(t) {
  949. for (let e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);
  950. }
  951. toArray() {
  952. return this.segments.slice(this.offset, this.limit());
  953. }
  954. static comparator(t, e) {
  955. const n = Math.min(t.length, e.length);
  956. for (let s = 0; s < n; s++) {
  957. const n = t.get(s), i = e.get(s);
  958. if (n < i) return -1;
  959. if (n > i) return 1;
  960. }
  961. return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;
  962. }
  963. }
  964. /**
  965. * A slash-separated path for navigating resources (documents and collections)
  966. * within Firestore.
  967. *
  968. * @internal
  969. */ class rt extends it {
  970. construct(t, e, n) {
  971. return new rt(t, e, n);
  972. }
  973. canonicalString() {
  974. // NOTE: The client is ignorant of any path segments containing escape
  975. // sequences (e.g. __id123__) and just passes them through raw (they exist
  976. // for legacy reasons and should not be used frequently).
  977. return this.toArray().join("/");
  978. }
  979. toString() {
  980. return this.canonicalString();
  981. }
  982. /**
  983. * Creates a resource path from the given slash-delimited string. If multiple
  984. * arguments are provided, all components are combined. Leading and trailing
  985. * slashes from all components are ignored.
  986. */ static fromString(...t) {
  987. // NOTE: The client is ignorant of any path segments containing escape
  988. // sequences (e.g. __id123__) and just passes them through raw (they exist
  989. // for legacy reasons and should not be used frequently).
  990. const e = [];
  991. for (const n of t) {
  992. if (n.indexOf("//") >= 0) throw new L(B.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);
  993. // Strip leading and traling slashed.
  994. e.push(...n.split("/").filter((t => t.length > 0)));
  995. }
  996. return new rt(e);
  997. }
  998. static emptyPath() {
  999. return new rt([]);
  1000. }
  1001. }
  1002. const ot = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
  1003. /**
  1004. * A dot-separated path for navigating sub-objects within a document.
  1005. * @internal
  1006. */ class ut extends it {
  1007. construct(t, e, n) {
  1008. return new ut(t, e, n);
  1009. }
  1010. /**
  1011. * Returns true if the string could be used as a segment in a field path
  1012. * without escaping.
  1013. */ static isValidIdentifier(t) {
  1014. return ot.test(t);
  1015. }
  1016. canonicalString() {
  1017. return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"),
  1018. ut.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join(".");
  1019. }
  1020. toString() {
  1021. return this.canonicalString();
  1022. }
  1023. /**
  1024. * Returns true if this field references the key of a document.
  1025. */ isKeyField() {
  1026. return 1 === this.length && "__name__" === this.get(0);
  1027. }
  1028. /**
  1029. * The field designating the key of a document.
  1030. */ static keyField() {
  1031. return new ut([ "__name__" ]);
  1032. }
  1033. /**
  1034. * Parses a field string from the given server-formatted string.
  1035. *
  1036. * - Splitting the empty string is not allowed (for now at least).
  1037. * - Empty segments within the string (e.g. if there are two consecutive
  1038. * separators) are not allowed.
  1039. *
  1040. * TODO(b/37244157): we should make this more strict. Right now, it allows
  1041. * non-identifier path components, even if they aren't escaped.
  1042. */ static fromServerFormat(t) {
  1043. const e = [];
  1044. let n = "", s = 0;
  1045. const i = () => {
  1046. if (0 === n.length) throw new L(B.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);
  1047. e.push(n), n = "";
  1048. };
  1049. let r = !1;
  1050. for (;s < t.length; ) {
  1051. const e = t[s];
  1052. if ("\\" === e) {
  1053. if (s + 1 === t.length) throw new L(B.INVALID_ARGUMENT, "Path has trailing escape character: " + t);
  1054. const e = t[s + 1];
  1055. if ("\\" !== e && "." !== e && "`" !== e) throw new L(B.INVALID_ARGUMENT, "Path has invalid escape sequence: " + t);
  1056. n += e, s += 2;
  1057. } else "`" === e ? (r = !r, s++) : "." !== e || r ? (n += e, s++) : (i(), s++);
  1058. }
  1059. if (i(), r) throw new L(B.INVALID_ARGUMENT, "Unterminated ` in path: " + t);
  1060. return new ut(e);
  1061. }
  1062. static emptyPath() {
  1063. return new ut([]);
  1064. }
  1065. }
  1066. /**
  1067. * @license
  1068. * Copyright 2017 Google LLC
  1069. *
  1070. * Licensed under the Apache License, Version 2.0 (the "License");
  1071. * you may not use this file except in compliance with the License.
  1072. * You may obtain a copy of the License at
  1073. *
  1074. * http://www.apache.org/licenses/LICENSE-2.0
  1075. *
  1076. * Unless required by applicable law or agreed to in writing, software
  1077. * distributed under the License is distributed on an "AS IS" BASIS,
  1078. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1079. * See the License for the specific language governing permissions and
  1080. * limitations under the License.
  1081. */
  1082. /**
  1083. * @internal
  1084. */ class ct {
  1085. constructor(t) {
  1086. this.path = t;
  1087. }
  1088. static fromPath(t) {
  1089. return new ct(rt.fromString(t));
  1090. }
  1091. static fromName(t) {
  1092. return new ct(rt.fromString(t).popFirst(5));
  1093. }
  1094. static empty() {
  1095. return new ct(rt.emptyPath());
  1096. }
  1097. get collectionGroup() {
  1098. return this.path.popLast().lastSegment();
  1099. }
  1100. /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) {
  1101. return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;
  1102. }
  1103. /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() {
  1104. return this.path.get(this.path.length - 2);
  1105. }
  1106. /** Returns the fully qualified path to the parent collection. */ getCollectionPath() {
  1107. return this.path.popLast();
  1108. }
  1109. isEqual(t) {
  1110. return null !== t && 0 === rt.comparator(this.path, t.path);
  1111. }
  1112. toString() {
  1113. return this.path.toString();
  1114. }
  1115. static comparator(t, e) {
  1116. return rt.comparator(t.path, e.path);
  1117. }
  1118. static isDocumentKey(t) {
  1119. return t.length % 2 == 0;
  1120. }
  1121. /**
  1122. * Creates and returns a new document key with the given segments.
  1123. *
  1124. * @param segments - The segments of the path to the document
  1125. * @returns A new instance of DocumentKey
  1126. */ static fromSegments(t) {
  1127. return new ct(new rt(t.slice()));
  1128. }
  1129. }
  1130. /**
  1131. * @license
  1132. * Copyright 2021 Google LLC
  1133. *
  1134. * Licensed under the Apache License, Version 2.0 (the "License");
  1135. * you may not use this file except in compliance with the License.
  1136. * You may obtain a copy of the License at
  1137. *
  1138. * http://www.apache.org/licenses/LICENSE-2.0
  1139. *
  1140. * Unless required by applicable law or agreed to in writing, software
  1141. * distributed under the License is distributed on an "AS IS" BASIS,
  1142. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1143. * See the License for the specific language governing permissions and
  1144. * limitations under the License.
  1145. */
  1146. /**
  1147. * The initial mutation batch id for each index. Gets updated during index
  1148. * backfill.
  1149. */
  1150. /**
  1151. * An index definition for field indexes in Firestore.
  1152. *
  1153. * Every index is associated with a collection. The definition contains a list
  1154. * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or
  1155. * `CONTAINS` for ArrayContains/ArrayContainsAny queries).
  1156. *
  1157. * Unlike the backend, the SDK does not differentiate between collection or
  1158. * collection group-scoped indices. Every index can be used for both single
  1159. * collection and collection group queries.
  1160. */
  1161. class at {
  1162. constructor(
  1163. /**
  1164. * The index ID. Returns -1 if the index ID is not available (e.g. the index
  1165. * has not yet been persisted).
  1166. */
  1167. t,
  1168. /** The collection ID this index applies to. */
  1169. e,
  1170. /** The field segments for this index. */
  1171. n,
  1172. /** Shows how up-to-date the index is for the current user. */
  1173. s) {
  1174. this.indexId = t, this.collectionGroup = e, this.fields = n, this.indexState = s;
  1175. }
  1176. }
  1177. /** An ID for an index that has not yet been added to persistence. */
  1178. /** Returns the ArrayContains/ArrayContainsAny segment for this index. */
  1179. function ht(t) {
  1180. return t.fields.find((t => 2 /* IndexKind.CONTAINS */ === t.kind));
  1181. }
  1182. /** Returns all directional (ascending/descending) segments for this index. */ function lt(t) {
  1183. return t.fields.filter((t => 2 /* IndexKind.CONTAINS */ !== t.kind));
  1184. }
  1185. /**
  1186. * Returns the order of the document key component for the given index.
  1187. *
  1188. * PORTING NOTE: This is only used in the Web IndexedDb implementation.
  1189. */
  1190. /**
  1191. * Compares indexes by collection group and segments. Ignores update time and
  1192. * index ID.
  1193. */
  1194. function ft(t, e) {
  1195. let n = Z(t.collectionGroup, e.collectionGroup);
  1196. if (0 !== n) return n;
  1197. for (let s = 0; s < Math.min(t.fields.length, e.fields.length); ++s) if (n = _t(t.fields[s], e.fields[s]),
  1198. 0 !== n) return n;
  1199. return Z(t.fields.length, e.fields.length);
  1200. }
  1201. /** Returns a debug representation of the field index */ at.UNKNOWN_ID = -1;
  1202. /** An index component consisting of field path and index type. */
  1203. class dt {
  1204. constructor(
  1205. /** The field path of the component. */
  1206. t,
  1207. /** The fields sorting order. */
  1208. e) {
  1209. this.fieldPath = t, this.kind = e;
  1210. }
  1211. }
  1212. function _t(t, e) {
  1213. const n = ut.comparator(t.fieldPath, e.fieldPath);
  1214. return 0 !== n ? n : Z(t.kind, e.kind);
  1215. }
  1216. /**
  1217. * Stores the "high water mark" that indicates how updated the Index is for the
  1218. * current user.
  1219. */ class wt {
  1220. constructor(
  1221. /**
  1222. * Indicates when the index was last updated (relative to other indexes).
  1223. */
  1224. t,
  1225. /** The the latest indexed read time, document and batch id. */
  1226. e) {
  1227. this.sequenceNumber = t, this.offset = e;
  1228. }
  1229. /** The state of an index that has not yet been backfilled. */ static empty() {
  1230. return new wt(0, yt.min());
  1231. }
  1232. }
  1233. /**
  1234. * Creates an offset that matches all documents with a read time higher than
  1235. * `readTime`.
  1236. */ function mt(t, e) {
  1237. // We want to create an offset that matches all documents with a read time
  1238. // greater than the provided read time. To do so, we technically need to
  1239. // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use
  1240. // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use
  1241. // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches
  1242. // all valid document IDs.
  1243. const n = t.toTimestamp().seconds, s = t.toTimestamp().nanoseconds + 1, i = st.fromTimestamp(1e9 === s ? new nt(n + 1, 0) : new nt(n, s));
  1244. return new yt(i, ct.empty(), e);
  1245. }
  1246. /** Creates a new offset based on the provided document. */ function gt(t) {
  1247. return new yt(t.readTime, t.key, -1);
  1248. }
  1249. /**
  1250. * Stores the latest read time, document and batch ID that were processed for an
  1251. * index.
  1252. */ class yt {
  1253. constructor(
  1254. /**
  1255. * The latest read time version that has been indexed by Firestore for this
  1256. * field index.
  1257. */
  1258. t,
  1259. /**
  1260. * The key of the last document that was indexed for this query. Use
  1261. * `DocumentKey.empty()` if no document has been indexed.
  1262. */
  1263. e,
  1264. /*
  1265. * The largest mutation batch id that's been processed by Firestore.
  1266. */
  1267. n) {
  1268. this.readTime = t, this.documentKey = e, this.largestBatchId = n;
  1269. }
  1270. /** Returns an offset that sorts before all regular offsets. */ static min() {
  1271. return new yt(st.min(), ct.empty(), -1);
  1272. }
  1273. /** Returns an offset that sorts after all regular offsets. */ static max() {
  1274. return new yt(st.max(), ct.empty(), -1);
  1275. }
  1276. }
  1277. function pt(t, e) {
  1278. let n = t.readTime.compareTo(e.readTime);
  1279. return 0 !== n ? n : (n = ct.comparator(t.documentKey, e.documentKey), 0 !== n ? n : Z(t.largestBatchId, e.largestBatchId));
  1280. }
  1281. /**
  1282. * @license
  1283. * Copyright 2020 Google LLC
  1284. *
  1285. * Licensed under the Apache License, Version 2.0 (the "License");
  1286. * you may not use this file except in compliance with the License.
  1287. * You may obtain a copy of the License at
  1288. *
  1289. * http://www.apache.org/licenses/LICENSE-2.0
  1290. *
  1291. * Unless required by applicable law or agreed to in writing, software
  1292. * distributed under the License is distributed on an "AS IS" BASIS,
  1293. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1294. * See the License for the specific language governing permissions and
  1295. * limitations under the License.
  1296. */ const It = "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";
  1297. /**
  1298. * A base class representing a persistence transaction, encapsulating both the
  1299. * transaction's sequence numbers as well as a list of onCommitted listeners.
  1300. *
  1301. * When you call Persistence.runTransaction(), it will create a transaction and
  1302. * pass it to your callback. You then pass it to any method that operates
  1303. * on persistence.
  1304. */ class Tt {
  1305. constructor() {
  1306. this.onCommittedListeners = [];
  1307. }
  1308. addOnCommittedListener(t) {
  1309. this.onCommittedListeners.push(t);
  1310. }
  1311. raiseOnCommittedEvent() {
  1312. this.onCommittedListeners.forEach((t => t()));
  1313. }
  1314. }
  1315. /**
  1316. * @license
  1317. * Copyright 2017 Google LLC
  1318. *
  1319. * Licensed under the Apache License, Version 2.0 (the "License");
  1320. * you may not use this file except in compliance with the License.
  1321. * You may obtain a copy of the License at
  1322. *
  1323. * http://www.apache.org/licenses/LICENSE-2.0
  1324. *
  1325. * Unless required by applicable law or agreed to in writing, software
  1326. * distributed under the License is distributed on an "AS IS" BASIS,
  1327. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1328. * See the License for the specific language governing permissions and
  1329. * limitations under the License.
  1330. */
  1331. /**
  1332. * Verifies the error thrown by a LocalStore operation. If a LocalStore
  1333. * operation fails because the primary lease has been taken by another client,
  1334. * we ignore the error (the persistence layer will immediately call
  1335. * `applyPrimaryLease` to propagate the primary state change). All other errors
  1336. * are re-thrown.
  1337. *
  1338. * @param err - An error returned by a LocalStore operation.
  1339. * @returns A Promise that resolves after we recovered, or the original error.
  1340. */ async function Et(t) {
  1341. if (t.code !== B.FAILED_PRECONDITION || t.message !== It) throw t;
  1342. C("LocalStore", "Unexpectedly lost primary lease");
  1343. }
  1344. /**
  1345. * @license
  1346. * Copyright 2017 Google LLC
  1347. *
  1348. * Licensed under the Apache License, Version 2.0 (the "License");
  1349. * you may not use this file except in compliance with the License.
  1350. * You may obtain a copy of the License at
  1351. *
  1352. * http://www.apache.org/licenses/LICENSE-2.0
  1353. *
  1354. * Unless required by applicable law or agreed to in writing, software
  1355. * distributed under the License is distributed on an "AS IS" BASIS,
  1356. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1357. * See the License for the specific language governing permissions and
  1358. * limitations under the License.
  1359. */
  1360. /**
  1361. * PersistencePromise is essentially a re-implementation of Promise except
  1362. * it has a .next() method instead of .then() and .next() and .catch() callbacks
  1363. * are executed synchronously when a PersistencePromise resolves rather than
  1364. * asynchronously (Promise implementations use setImmediate() or similar).
  1365. *
  1366. * This is necessary to interoperate with IndexedDB which will automatically
  1367. * commit transactions if control is returned to the event loop without
  1368. * synchronously initiating another operation on the transaction.
  1369. *
  1370. * NOTE: .then() and .catch() only allow a single consumer, unlike normal
  1371. * Promises.
  1372. */ class At {
  1373. constructor(t) {
  1374. // NOTE: next/catchCallback will always point to our own wrapper functions,
  1375. // not the user's raw next() or catch() callbacks.
  1376. this.nextCallback = null, this.catchCallback = null,
  1377. // When the operation resolves, we'll set result or error and mark isDone.
  1378. this.result = void 0, this.error = void 0, this.isDone = !1,
  1379. // Set to true when .then() or .catch() are called and prevents additional
  1380. // chaining.
  1381. this.callbackAttached = !1, t((t => {
  1382. this.isDone = !0, this.result = t, this.nextCallback &&
  1383. // value should be defined unless T is Void, but we can't express
  1384. // that in the type system.
  1385. this.nextCallback(t);
  1386. }), (t => {
  1387. this.isDone = !0, this.error = t, this.catchCallback && this.catchCallback(t);
  1388. }));
  1389. }
  1390. catch(t) {
  1391. return this.next(void 0, t);
  1392. }
  1393. next(t, e) {
  1394. return this.callbackAttached && O(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(e, this.error) : this.wrapSuccess(t, this.result) : new At(((n, s) => {
  1395. this.nextCallback = e => {
  1396. this.wrapSuccess(t, e).next(n, s);
  1397. }, this.catchCallback = t => {
  1398. this.wrapFailure(e, t).next(n, s);
  1399. };
  1400. }));
  1401. }
  1402. toPromise() {
  1403. return new Promise(((t, e) => {
  1404. this.next(t, e);
  1405. }));
  1406. }
  1407. wrapUserFunction(t) {
  1408. try {
  1409. const e = t();
  1410. return e instanceof At ? e : At.resolve(e);
  1411. } catch (t) {
  1412. return At.reject(t);
  1413. }
  1414. }
  1415. wrapSuccess(t, e) {
  1416. return t ? this.wrapUserFunction((() => t(e))) : At.resolve(e);
  1417. }
  1418. wrapFailure(t, e) {
  1419. return t ? this.wrapUserFunction((() => t(e))) : At.reject(e);
  1420. }
  1421. static resolve(t) {
  1422. return new At(((e, n) => {
  1423. e(t);
  1424. }));
  1425. }
  1426. static reject(t) {
  1427. return new At(((e, n) => {
  1428. n(t);
  1429. }));
  1430. }
  1431. static waitFor(
  1432. // Accept all Promise types in waitFor().
  1433. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1434. t) {
  1435. return new At(((e, n) => {
  1436. let s = 0, i = 0, r = !1;
  1437. t.forEach((t => {
  1438. ++s, t.next((() => {
  1439. ++i, r && i === s && e();
  1440. }), (t => n(t)));
  1441. })), r = !0, i === s && e();
  1442. }));
  1443. }
  1444. /**
  1445. * Given an array of predicate functions that asynchronously evaluate to a
  1446. * boolean, implements a short-circuiting `or` between the results. Predicates
  1447. * will be evaluated until one of them returns `true`, then stop. The final
  1448. * result will be whether any of them returned `true`.
  1449. */ static or(t) {
  1450. let e = At.resolve(!1);
  1451. for (const n of t) e = e.next((t => t ? At.resolve(t) : n()));
  1452. return e;
  1453. }
  1454. static forEach(t, e) {
  1455. const n = [];
  1456. return t.forEach(((t, s) => {
  1457. n.push(e.call(this, t, s));
  1458. })), this.waitFor(n);
  1459. }
  1460. /**
  1461. * Concurrently map all array elements through asynchronous function.
  1462. */ static mapArray(t, e) {
  1463. return new At(((n, s) => {
  1464. const i = t.length, r = new Array(i);
  1465. let o = 0;
  1466. for (let u = 0; u < i; u++) {
  1467. const c = u;
  1468. e(t[c]).next((t => {
  1469. r[c] = t, ++o, o === i && n(r);
  1470. }), (t => s(t)));
  1471. }
  1472. }));
  1473. }
  1474. /**
  1475. * An alternative to recursive PersistencePromise calls, that avoids
  1476. * potential memory problems from unbounded chains of promises.
  1477. *
  1478. * The `action` will be called repeatedly while `condition` is true.
  1479. */ static doWhile(t, e) {
  1480. return new At(((n, s) => {
  1481. const i = () => {
  1482. !0 === t() ? e().next((() => {
  1483. i();
  1484. }), s) : n();
  1485. };
  1486. i();
  1487. }));
  1488. }
  1489. }
  1490. /**
  1491. * @license
  1492. * Copyright 2017 Google LLC
  1493. *
  1494. * Licensed under the Apache License, Version 2.0 (the "License");
  1495. * you may not use this file except in compliance with the License.
  1496. * You may obtain a copy of the License at
  1497. *
  1498. * http://www.apache.org/licenses/LICENSE-2.0
  1499. *
  1500. * Unless required by applicable law or agreed to in writing, software
  1501. * distributed under the License is distributed on an "AS IS" BASIS,
  1502. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1503. * See the License for the specific language governing permissions and
  1504. * limitations under the License.
  1505. */
  1506. // References to `window` are guarded by SimpleDb.isAvailable()
  1507. /* eslint-disable no-restricted-globals */
  1508. /**
  1509. * Wraps an IDBTransaction and exposes a store() method to get a handle to a
  1510. * specific object store.
  1511. */
  1512. class Rt {
  1513. constructor(t, e) {
  1514. this.action = t, this.transaction = e, this.aborted = !1,
  1515. /**
  1516. * A `Promise` that resolves with the result of the IndexedDb transaction.
  1517. */
  1518. this.P = new q, this.transaction.oncomplete = () => {
  1519. this.P.resolve();
  1520. }, this.transaction.onabort = () => {
  1521. e.error ? this.P.reject(new vt(t, e.error)) : this.P.resolve();
  1522. }, this.transaction.onerror = e => {
  1523. const n = xt(e.target.error);
  1524. this.P.reject(new vt(t, n));
  1525. };
  1526. }
  1527. static open(t, e, n, s) {
  1528. try {
  1529. return new Rt(e, t.transaction(s, n));
  1530. } catch (t) {
  1531. throw new vt(e, t);
  1532. }
  1533. }
  1534. get v() {
  1535. return this.P.promise;
  1536. }
  1537. abort(t) {
  1538. t && this.P.reject(t), this.aborted || (C("SimpleDb", "Aborting transaction:", t ? t.message : "Client-initiated abort"),
  1539. this.aborted = !0, this.transaction.abort());
  1540. }
  1541. V() {
  1542. // If the browser supports V3 IndexedDB, we invoke commit() explicitly to
  1543. // speed up index DB processing if the event loop remains blocks.
  1544. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1545. const t = this.transaction;
  1546. this.aborted || "function" != typeof t.commit || t.commit();
  1547. }
  1548. /**
  1549. * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All
  1550. * operations performed on the SimpleDbStore happen within the context of this
  1551. * transaction and it cannot be used anymore once the transaction is
  1552. * completed.
  1553. *
  1554. * Note that we can't actually enforce that the KeyType and ValueType are
  1555. * correct, but they allow type safety through the rest of the consuming code.
  1556. */ store(t) {
  1557. const e = this.transaction.objectStore(t);
  1558. return new St(e);
  1559. }
  1560. }
  1561. /**
  1562. * Provides a wrapper around IndexedDb with a simplified interface that uses
  1563. * Promise-like return values to chain operations. Real promises cannot be used
  1564. * since .then() continuations are executed asynchronously (e.g. via
  1565. * .setImmediate), which would cause IndexedDB to end the transaction.
  1566. * See PersistencePromise for more details.
  1567. */ class bt {
  1568. /*
  1569. * Creates a new SimpleDb wrapper for IndexedDb database `name`.
  1570. *
  1571. * Note that `version` must not be a downgrade. IndexedDB does not support
  1572. * downgrading the schema version. We currently do not support any way to do
  1573. * versioning outside of IndexedDB's versioning mechanism, as only
  1574. * version-upgrade transactions are allowed to do things like create
  1575. * objectstores.
  1576. */
  1577. constructor(t, e, n) {
  1578. this.name = t, this.version = e, this.S = n;
  1579. // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the
  1580. // bug we're checking for should exist in iOS >= 12.2 and < 13, but for
  1581. // whatever reason it's much harder to hit after 12.2 so we only proactively
  1582. // log on 12.2.
  1583. 12.2 === bt.D(getUA()) && x("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.");
  1584. }
  1585. /** Deletes the specified database. */ static delete(t) {
  1586. return C("SimpleDb", "Removing database:", t), Dt(window.indexedDB.deleteDatabase(t)).toPromise();
  1587. }
  1588. /** Returns true if IndexedDB is available in the current environment. */ static C() {
  1589. if (!isIndexedDBAvailable()) return !1;
  1590. if (bt.N()) return !0;
  1591. // We extensively use indexed array values and compound keys,
  1592. // which IE and Edge do not support. However, they still have indexedDB
  1593. // defined on the window, so we need to check for them here and make sure
  1594. // to return that persistence is not enabled for those browsers.
  1595. // For tracking support of this feature, see here:
  1596. // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/
  1597. // Check the UA string to find out the browser.
  1598. const t = getUA(), e = bt.D(t), n = 0 < e && e < 10, s = bt.k(t), i = 0 < s && s < 4.5;
  1599. // IE 10
  1600. // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
  1601. // IE 11
  1602. // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
  1603. // Edge
  1604. // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,
  1605. // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
  1606. // iOS Safari: Disable for users running iOS version < 10.
  1607. return !(t.indexOf("MSIE ") > 0 || t.indexOf("Trident/") > 0 || t.indexOf("Edge/") > 0 || n || i);
  1608. }
  1609. /**
  1610. * Returns true if the backing IndexedDB store is the Node IndexedDBShim
  1611. * (see https://github.com/axemclion/IndexedDBShim).
  1612. */ static N() {
  1613. var t;
  1614. return "undefined" != typeof process && "YES" === (null === (t = process.env) || void 0 === t ? void 0 : t.O);
  1615. }
  1616. /** Helper to get a typed SimpleDbStore from a transaction. */ static M(t, e) {
  1617. return t.store(e);
  1618. }
  1619. // visible for testing
  1620. /** Parse User Agent to determine iOS version. Returns -1 if not found. */
  1621. static D(t) {
  1622. const e = t.match(/i(?:phone|pad|pod) os ([\d_]+)/i), n = e ? e[1].split("_").slice(0, 2).join(".") : "-1";
  1623. return Number(n);
  1624. }
  1625. // visible for testing
  1626. /** Parse User Agent to determine Android version. Returns -1 if not found. */
  1627. static k(t) {
  1628. const e = t.match(/Android ([\d.]+)/i), n = e ? e[1].split(".").slice(0, 2).join(".") : "-1";
  1629. return Number(n);
  1630. }
  1631. /**
  1632. * Opens the specified database, creating or upgrading it if necessary.
  1633. */ async F(t) {
  1634. return this.db || (C("SimpleDb", "Opening database:", this.name), this.db = await new Promise(((e, n) => {
  1635. // TODO(mikelehen): Investigate browser compatibility.
  1636. // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
  1637. // suggests IE9 and older WebKit browsers handle upgrade
  1638. // differently. They expect setVersion, as described here:
  1639. // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion
  1640. const s = indexedDB.open(this.name, this.version);
  1641. s.onsuccess = t => {
  1642. const n = t.target.result;
  1643. e(n);
  1644. }, s.onblocked = () => {
  1645. n(new vt(t, "Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."));
  1646. }, s.onerror = e => {
  1647. const s = e.target.error;
  1648. "VersionError" === s.name ? n(new L(B.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" === s.name ? n(new L(B.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: " + s)) : n(new vt(t, s));
  1649. }, s.onupgradeneeded = t => {
  1650. C("SimpleDb", 'Database "' + this.name + '" requires upgrade from version:', t.oldVersion);
  1651. const e = t.target.result;
  1652. this.S.$(e, s.transaction, t.oldVersion, this.version).next((() => {
  1653. C("SimpleDb", "Database upgrade to version " + this.version + " complete");
  1654. }));
  1655. };
  1656. }))), this.B && (this.db.onversionchange = t => this.B(t)), this.db;
  1657. }
  1658. L(t) {
  1659. this.B = t, this.db && (this.db.onversionchange = e => t(e));
  1660. }
  1661. async runTransaction(t, e, n, s) {
  1662. const i = "readonly" === e;
  1663. let r = 0;
  1664. for (;;) {
  1665. ++r;
  1666. try {
  1667. this.db = await this.F(t);
  1668. const e = Rt.open(this.db, t, i ? "readonly" : "readwrite", n), r = s(e).next((t => (e.V(),
  1669. t))).catch((t => (
  1670. // Abort the transaction if there was an error.
  1671. e.abort(t), At.reject(t)))).toPromise();
  1672. // As noted above, errors are propagated by aborting the transaction. So
  1673. // we swallow any error here to avoid the browser logging it as unhandled.
  1674. return r.catch((() => {})),
  1675. // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to
  1676. // fire), but still return the original transactionFnResult back to the
  1677. // caller.
  1678. await e.v, r;
  1679. } catch (t) {
  1680. const e = t, n = "FirebaseError" !== e.name && r < 3;
  1681. // TODO(schmidt-sebastian): We could probably be smarter about this and
  1682. // not retry exceptions that are likely unrecoverable (such as quota
  1683. // exceeded errors).
  1684. // Note: We cannot use an instanceof check for FirestoreException, since the
  1685. // exception is wrapped in a generic error by our async/await handling.
  1686. if (C("SimpleDb", "Transaction failed with error:", e.message, "Retrying:", n),
  1687. this.close(), !n) return Promise.reject(e);
  1688. }
  1689. }
  1690. }
  1691. close() {
  1692. this.db && this.db.close(), this.db = void 0;
  1693. }
  1694. }
  1695. /**
  1696. * A controller for iterating over a key range or index. It allows an iterate
  1697. * callback to delete the currently-referenced object, or jump to a new key
  1698. * within the key range or index.
  1699. */ class Pt {
  1700. constructor(t) {
  1701. this.q = t, this.U = !1, this.K = null;
  1702. }
  1703. get isDone() {
  1704. return this.U;
  1705. }
  1706. get G() {
  1707. return this.K;
  1708. }
  1709. set cursor(t) {
  1710. this.q = t;
  1711. }
  1712. /**
  1713. * This function can be called to stop iteration at any point.
  1714. */ done() {
  1715. this.U = !0;
  1716. }
  1717. /**
  1718. * This function can be called to skip to that next key, which could be
  1719. * an index or a primary key.
  1720. */ j(t) {
  1721. this.K = t;
  1722. }
  1723. /**
  1724. * Delete the current cursor value from the object store.
  1725. *
  1726. * NOTE: You CANNOT do this with a keysOnly query.
  1727. */ delete() {
  1728. return Dt(this.q.delete());
  1729. }
  1730. }
  1731. /** An error that wraps exceptions that thrown during IndexedDB execution. */ class vt extends L {
  1732. constructor(t, e) {
  1733. super(B.UNAVAILABLE, `IndexedDB transaction '${t}' failed: ${e}`), this.name = "IndexedDbTransactionError";
  1734. }
  1735. }
  1736. /** Verifies whether `e` is an IndexedDbTransactionError. */ function Vt(t) {
  1737. // Use name equality, as instanceof checks on errors don't work with errors
  1738. // that wrap other errors.
  1739. return "IndexedDbTransactionError" === t.name;
  1740. }
  1741. /**
  1742. * A wrapper around an IDBObjectStore providing an API that:
  1743. *
  1744. * 1) Has generic KeyType / ValueType parameters to provide strongly-typed
  1745. * methods for acting against the object store.
  1746. * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every
  1747. * method return a PersistencePromise instead.
  1748. * 3) Provides a higher-level API to avoid needing to do excessive wrapping of
  1749. * intermediate IndexedDB types (IDBCursorWithValue, etc.)
  1750. */ class St {
  1751. constructor(t) {
  1752. this.store = t;
  1753. }
  1754. put(t, e) {
  1755. let n;
  1756. return void 0 !== e ? (C("SimpleDb", "PUT", this.store.name, t, e), n = this.store.put(e, t)) : (C("SimpleDb", "PUT", this.store.name, "<auto-key>", t),
  1757. n = this.store.put(t)), Dt(n);
  1758. }
  1759. /**
  1760. * Adds a new value into an Object Store and returns the new key. Similar to
  1761. * IndexedDb's `add()`, this method will fail on primary key collisions.
  1762. *
  1763. * @param value - The object to write.
  1764. * @returns The key of the value to add.
  1765. */ add(t) {
  1766. C("SimpleDb", "ADD", this.store.name, t, t);
  1767. return Dt(this.store.add(t));
  1768. }
  1769. /**
  1770. * Gets the object with the specified key from the specified store, or null
  1771. * if no object exists with the specified key.
  1772. *
  1773. * @key The key of the object to get.
  1774. * @returns The object with the specified key or null if no object exists.
  1775. */ get(t) {
  1776. // We're doing an unsafe cast to ValueType.
  1777. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1778. return Dt(this.store.get(t)).next((e => (
  1779. // Normalize nonexistence to null.
  1780. void 0 === e && (e = null), C("SimpleDb", "GET", this.store.name, t, e), e)));
  1781. }
  1782. delete(t) {
  1783. C("SimpleDb", "DELETE", this.store.name, t);
  1784. return Dt(this.store.delete(t));
  1785. }
  1786. /**
  1787. * If we ever need more of the count variants, we can add overloads. For now,
  1788. * all we need is to count everything in a store.
  1789. *
  1790. * Returns the number of rows in the store.
  1791. */ count() {
  1792. C("SimpleDb", "COUNT", this.store.name);
  1793. return Dt(this.store.count());
  1794. }
  1795. W(t, e) {
  1796. const n = this.options(t, e);
  1797. // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly
  1798. // 20% faster. Unfortunately, getAll() does not support custom indices.
  1799. if (n.index || "function" != typeof this.store.getAll) {
  1800. const t = this.cursor(n), e = [];
  1801. return this.H(t, ((t, n) => {
  1802. e.push(n);
  1803. })).next((() => e));
  1804. }
  1805. {
  1806. const t = this.store.getAll(n.range);
  1807. return new At(((e, n) => {
  1808. t.onerror = t => {
  1809. n(t.target.error);
  1810. }, t.onsuccess = t => {
  1811. e(t.target.result);
  1812. };
  1813. }));
  1814. }
  1815. }
  1816. /**
  1817. * Loads the first `count` elements from the provided index range. Loads all
  1818. * elements if no limit is provided.
  1819. */ J(t, e) {
  1820. const n = this.store.getAll(t, null === e ? void 0 : e);
  1821. return new At(((t, e) => {
  1822. n.onerror = t => {
  1823. e(t.target.error);
  1824. }, n.onsuccess = e => {
  1825. t(e.target.result);
  1826. };
  1827. }));
  1828. }
  1829. Y(t, e) {
  1830. C("SimpleDb", "DELETE ALL", this.store.name);
  1831. const n = this.options(t, e);
  1832. n.X = !1;
  1833. const s = this.cursor(n);
  1834. return this.H(s, ((t, e, n) => n.delete()));
  1835. }
  1836. Z(t, e) {
  1837. let n;
  1838. e ? n = t : (n = {}, e = t);
  1839. const s = this.cursor(n);
  1840. return this.H(s, e);
  1841. }
  1842. /**
  1843. * Iterates over a store, but waits for the given callback to complete for
  1844. * each entry before iterating the next entry. This allows the callback to do
  1845. * asynchronous work to determine if this iteration should continue.
  1846. *
  1847. * The provided callback should return `true` to continue iteration, and
  1848. * `false` otherwise.
  1849. */ tt(t) {
  1850. const e = this.cursor({});
  1851. return new At(((n, s) => {
  1852. e.onerror = t => {
  1853. const e = xt(t.target.error);
  1854. s(e);
  1855. }, e.onsuccess = e => {
  1856. const s = e.target.result;
  1857. s ? t(s.primaryKey, s.value).next((t => {
  1858. t ? s.continue() : n();
  1859. })) : n();
  1860. };
  1861. }));
  1862. }
  1863. H(t, e) {
  1864. const n = [];
  1865. return new At(((s, i) => {
  1866. t.onerror = t => {
  1867. i(t.target.error);
  1868. }, t.onsuccess = t => {
  1869. const i = t.target.result;
  1870. if (!i) return void s();
  1871. const r = new Pt(i), o = e(i.primaryKey, i.value, r);
  1872. if (o instanceof At) {
  1873. const t = o.catch((t => (r.done(), At.reject(t))));
  1874. n.push(t);
  1875. }
  1876. r.isDone ? s() : null === r.G ? i.continue() : i.continue(r.G);
  1877. };
  1878. })).next((() => At.waitFor(n)));
  1879. }
  1880. options(t, e) {
  1881. let n;
  1882. return void 0 !== t && ("string" == typeof t ? n = t : e = t), {
  1883. index: n,
  1884. range: e
  1885. };
  1886. }
  1887. cursor(t) {
  1888. let e = "next";
  1889. if (t.reverse && (e = "prev"), t.index) {
  1890. const n = this.store.index(t.index);
  1891. return t.X ? n.openKeyCursor(t.range, e) : n.openCursor(t.range, e);
  1892. }
  1893. return this.store.openCursor(t.range, e);
  1894. }
  1895. }
  1896. /**
  1897. * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror
  1898. * handlers to resolve / reject the PersistencePromise as appropriate.
  1899. */ function Dt(t) {
  1900. return new At(((e, n) => {
  1901. t.onsuccess = t => {
  1902. const n = t.target.result;
  1903. e(n);
  1904. }, t.onerror = t => {
  1905. const e = xt(t.target.error);
  1906. n(e);
  1907. };
  1908. }));
  1909. }
  1910. // Guard so we only report the error once.
  1911. let Ct = !1;
  1912. function xt(t) {
  1913. const e = bt.D(getUA());
  1914. if (e >= 12.2 && e < 13) {
  1915. const e = "An internal error was encountered in the Indexed Database server";
  1916. if (t.message.indexOf(e) >= 0) {
  1917. // Wrap error in a more descriptive one.
  1918. const t = new L("internal", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${e}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);
  1919. return Ct || (Ct = !0,
  1920. // Throw a global exception outside of this promise chain, for the user to
  1921. // potentially catch.
  1922. setTimeout((() => {
  1923. throw t;
  1924. }), 0)), t;
  1925. }
  1926. }
  1927. return t;
  1928. }
  1929. /** This class is responsible for the scheduling of Index Backfiller. */
  1930. class Nt {
  1931. constructor(t, e) {
  1932. this.asyncQueue = t, this.et = e, this.task = null;
  1933. }
  1934. start() {
  1935. this.nt(15e3);
  1936. }
  1937. stop() {
  1938. this.task && (this.task.cancel(), this.task = null);
  1939. }
  1940. get started() {
  1941. return null !== this.task;
  1942. }
  1943. nt(t) {
  1944. C("IndexBackiller", `Scheduled in ${t}ms`), this.task = this.asyncQueue.enqueueAfterDelay("index_backfill" /* TimerId.IndexBackfill */ , t, (async () => {
  1945. this.task = null;
  1946. try {
  1947. C("IndexBackiller", `Documents written: ${await this.et.st()}`);
  1948. } catch (t) {
  1949. Vt(t) ? C("IndexBackiller", "Ignoring IndexedDB error during index backfill: ", t) : await Et(t);
  1950. }
  1951. await this.nt(6e4);
  1952. }));
  1953. }
  1954. }
  1955. /** Implements the steps for backfilling indexes. */ class kt {
  1956. constructor(
  1957. /**
  1958. * LocalStore provides access to IndexManager and LocalDocumentView.
  1959. * These properties will update when the user changes. Consequently,
  1960. * making a local copy of IndexManager and LocalDocumentView will require
  1961. * updates over time. The simpler solution is to rely on LocalStore to have
  1962. * an up-to-date references to IndexManager and LocalDocumentStore.
  1963. */
  1964. t, e) {
  1965. this.localStore = t, this.persistence = e;
  1966. }
  1967. async st(t = 50) {
  1968. return this.persistence.runTransaction("Backfill Indexes", "readwrite-primary", (e => this.it(e, t)));
  1969. }
  1970. /** Writes index entries until the cap is reached. Returns the number of documents processed. */ it(t, e) {
  1971. const n = new Set;
  1972. let s = e, i = !0;
  1973. return At.doWhile((() => !0 === i && s > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(t).next((e => {
  1974. if (null !== e && !n.has(e)) return C("IndexBackiller", `Processing collection: ${e}`),
  1975. this.rt(t, e, s).next((t => {
  1976. s -= t, n.add(e);
  1977. }));
  1978. i = !1;
  1979. })))).next((() => e - s));
  1980. }
  1981. /**
  1982. * Writes entries for the provided collection group. Returns the number of documents processed.
  1983. */ rt(t, e, n) {
  1984. // Use the earliest offset of all field indexes to query the local cache.
  1985. return this.localStore.indexManager.getMinOffsetFromCollectionGroup(t, e).next((s => this.localStore.localDocuments.getNextDocuments(t, e, s, n).next((n => {
  1986. const i = n.changes;
  1987. return this.localStore.indexManager.updateIndexEntries(t, i).next((() => this.ot(s, n))).next((n => (C("IndexBackiller", `Updating offset: ${n}`),
  1988. this.localStore.indexManager.updateCollectionGroup(t, e, n)))).next((() => i.size));
  1989. }))));
  1990. }
  1991. /** Returns the next offset based on the provided documents. */ ot(t, e) {
  1992. let n = t;
  1993. return e.changes.forEach(((t, e) => {
  1994. const s = gt(e);
  1995. pt(s, n) > 0 && (n = s);
  1996. })), new yt(n.readTime, n.documentKey, Math.max(e.batchId, t.largestBatchId));
  1997. }
  1998. }
  1999. /**
  2000. * @license
  2001. * Copyright 2018 Google LLC
  2002. *
  2003. * Licensed under the Apache License, Version 2.0 (the "License");
  2004. * you may not use this file except in compliance with the License.
  2005. * You may obtain a copy of the License at
  2006. *
  2007. * http://www.apache.org/licenses/LICENSE-2.0
  2008. *
  2009. * Unless required by applicable law or agreed to in writing, software
  2010. * distributed under the License is distributed on an "AS IS" BASIS,
  2011. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2012. * See the License for the specific language governing permissions and
  2013. * limitations under the License.
  2014. */
  2015. /**
  2016. * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to
  2017. * exceed. All subsequent calls to next will return increasing values. If provided with a
  2018. * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as
  2019. * well as write out sequence numbers that it produces via `next()`.
  2020. */ class Ot {
  2021. constructor(t, e) {
  2022. this.previousValue = t, e && (e.sequenceNumberHandler = t => this.ut(t), this.ct = t => e.writeSequenceNumber(t));
  2023. }
  2024. ut(t) {
  2025. return this.previousValue = Math.max(t, this.previousValue), this.previousValue;
  2026. }
  2027. next() {
  2028. const t = ++this.previousValue;
  2029. return this.ct && this.ct(t), t;
  2030. }
  2031. }
  2032. Ot.at = -1;
  2033. /**
  2034. * @license
  2035. * Copyright 2017 Google LLC
  2036. *
  2037. * Licensed under the Apache License, Version 2.0 (the "License");
  2038. * you may not use this file except in compliance with the License.
  2039. * You may obtain a copy of the License at
  2040. *
  2041. * http://www.apache.org/licenses/LICENSE-2.0
  2042. *
  2043. * Unless required by applicable law or agreed to in writing, software
  2044. * distributed under the License is distributed on an "AS IS" BASIS,
  2045. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2046. * See the License for the specific language governing permissions and
  2047. * limitations under the License.
  2048. */
  2049. class Mt {
  2050. /**
  2051. * Constructs a DatabaseInfo using the provided host, databaseId and
  2052. * persistenceKey.
  2053. *
  2054. * @param databaseId - The database to use.
  2055. * @param appId - The Firebase App Id.
  2056. * @param persistenceKey - A unique identifier for this Firestore's local
  2057. * storage (used in conjunction with the databaseId).
  2058. * @param host - The Firestore backend host to connect to.
  2059. * @param ssl - Whether to use SSL when connecting.
  2060. * @param forceLongPolling - Whether to use the forceLongPolling option
  2061. * when using WebChannel as the network transport.
  2062. * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
  2063. * option when using WebChannel as the network transport.
  2064. * @param useFetchStreams Whether to use the Fetch API instead of
  2065. * XMLHTTPRequest
  2066. */
  2067. constructor(t, e, n, s, i, r, o, u) {
  2068. this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = s, this.ssl = i,
  2069. this.forceLongPolling = r, this.autoDetectLongPolling = o, this.useFetchStreams = u;
  2070. }
  2071. }
  2072. /** The default database name for a project. */
  2073. /**
  2074. * Represents the database ID a Firestore client is associated with.
  2075. * @internal
  2076. */
  2077. class Ft {
  2078. constructor(t, e) {
  2079. this.projectId = t, this.database = e || "(default)";
  2080. }
  2081. static empty() {
  2082. return new Ft("", "");
  2083. }
  2084. get isDefaultDatabase() {
  2085. return "(default)" === this.database;
  2086. }
  2087. isEqual(t) {
  2088. return t instanceof Ft && t.projectId === this.projectId && t.database === this.database;
  2089. }
  2090. }
  2091. /**
  2092. * @license
  2093. * Copyright 2017 Google LLC
  2094. *
  2095. * Licensed under the Apache License, Version 2.0 (the "License");
  2096. * you may not use this file except in compliance with the License.
  2097. * You may obtain a copy of the License at
  2098. *
  2099. * http://www.apache.org/licenses/LICENSE-2.0
  2100. *
  2101. * Unless required by applicable law or agreed to in writing, software
  2102. * distributed under the License is distributed on an "AS IS" BASIS,
  2103. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2104. * See the License for the specific language governing permissions and
  2105. * limitations under the License.
  2106. */
  2107. function $t(t) {
  2108. let e = 0;
  2109. for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e++;
  2110. return e;
  2111. }
  2112. function Bt(t, e) {
  2113. for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);
  2114. }
  2115. function Lt(t) {
  2116. for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;
  2117. return !0;
  2118. }
  2119. /**
  2120. * @license
  2121. * Copyright 2017 Google LLC
  2122. *
  2123. * Licensed under the Apache License, Version 2.0 (the "License");
  2124. * you may not use this file except in compliance with the License.
  2125. * You may obtain a copy of the License at
  2126. *
  2127. * http://www.apache.org/licenses/LICENSE-2.0
  2128. *
  2129. * Unless required by applicable law or agreed to in writing, software
  2130. * distributed under the License is distributed on an "AS IS" BASIS,
  2131. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2132. * See the License for the specific language governing permissions and
  2133. * limitations under the License.
  2134. */
  2135. /** Sentinel value that sorts before any Mutation Batch ID. */
  2136. /**
  2137. * Returns whether a variable is either undefined or null.
  2138. */
  2139. function qt(t) {
  2140. return null == t;
  2141. }
  2142. /** Returns whether the value represents -0. */ function Ut(t) {
  2143. // Detect if the value is -0.0. Based on polyfill from
  2144. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  2145. return 0 === t && 1 / t == -1 / 0;
  2146. }
  2147. /**
  2148. * Returns whether a value is an integer and in the safe integer range
  2149. * @param value - The value to test for being an integer and in the safe range
  2150. */ function Kt(t) {
  2151. return "number" == typeof t && Number.isInteger(t) && !Ut(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;
  2152. }
  2153. /**
  2154. * @license
  2155. * Copyright 2020 Google LLC
  2156. *
  2157. * Licensed under the Apache License, Version 2.0 (the "License");
  2158. * you may not use this file except in compliance with the License.
  2159. * You may obtain a copy of the License at
  2160. *
  2161. * http://www.apache.org/licenses/LICENSE-2.0
  2162. *
  2163. * Unless required by applicable law or agreed to in writing, software
  2164. * distributed under the License is distributed on an "AS IS" BASIS,
  2165. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2166. * See the License for the specific language governing permissions and
  2167. * limitations under the License.
  2168. */
  2169. /** Converts a Base64 encoded string to a binary string. */
  2170. /** True if and only if the Base64 conversion functions are available. */
  2171. function Gt() {
  2172. return "undefined" != typeof atob;
  2173. }
  2174. /**
  2175. * @license
  2176. * Copyright 2020 Google LLC
  2177. *
  2178. * Licensed under the Apache License, Version 2.0 (the "License");
  2179. * you may not use this file except in compliance with the License.
  2180. * You may obtain a copy of the License at
  2181. *
  2182. * http://www.apache.org/licenses/LICENSE-2.0
  2183. *
  2184. * Unless required by applicable law or agreed to in writing, software
  2185. * distributed under the License is distributed on an "AS IS" BASIS,
  2186. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2187. * See the License for the specific language governing permissions and
  2188. * limitations under the License.
  2189. */
  2190. /**
  2191. * Immutable class that represents a "proto" byte string.
  2192. *
  2193. * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
  2194. * sent on the wire. This class abstracts away this differentiation by holding
  2195. * the proto byte string in a common class that must be converted into a string
  2196. * before being sent as a proto.
  2197. * @internal
  2198. */ class Qt {
  2199. constructor(t) {
  2200. this.binaryString = t;
  2201. }
  2202. static fromBase64String(t) {
  2203. const e = atob(t);
  2204. return new Qt(e);
  2205. }
  2206. static fromUint8Array(t) {
  2207. // TODO(indexing); Remove the copy of the byte string here as this method
  2208. // is frequently called during indexing.
  2209. const e =
  2210. /**
  2211. * Helper function to convert an Uint8array to a binary string.
  2212. */
  2213. function(t) {
  2214. let e = "";
  2215. for (let n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]);
  2216. return e;
  2217. }
  2218. /**
  2219. * Helper function to convert a binary string to an Uint8Array.
  2220. */ (t);
  2221. return new Qt(e);
  2222. }
  2223. [Symbol.iterator]() {
  2224. let t = 0;
  2225. return {
  2226. next: () => t < this.binaryString.length ? {
  2227. value: this.binaryString.charCodeAt(t++),
  2228. done: !1
  2229. } : {
  2230. value: void 0,
  2231. done: !0
  2232. }
  2233. };
  2234. }
  2235. toBase64() {
  2236. return t = this.binaryString, btoa(t);
  2237. /** Converts a binary string to a Base64 encoded string. */
  2238. var t;
  2239. }
  2240. toUint8Array() {
  2241. return function(t) {
  2242. const e = new Uint8Array(t.length);
  2243. for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);
  2244. return e;
  2245. }
  2246. /**
  2247. * @license
  2248. * Copyright 2020 Google LLC
  2249. *
  2250. * Licensed under the Apache License, Version 2.0 (the "License");
  2251. * you may not use this file except in compliance with the License.
  2252. * You may obtain a copy of the License at
  2253. *
  2254. * http://www.apache.org/licenses/LICENSE-2.0
  2255. *
  2256. * Unless required by applicable law or agreed to in writing, software
  2257. * distributed under the License is distributed on an "AS IS" BASIS,
  2258. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2259. * See the License for the specific language governing permissions and
  2260. * limitations under the License.
  2261. */
  2262. // A RegExp matching ISO 8601 UTC timestamps with optional fraction.
  2263. (this.binaryString);
  2264. }
  2265. approximateByteSize() {
  2266. return 2 * this.binaryString.length;
  2267. }
  2268. compareTo(t) {
  2269. return Z(this.binaryString, t.binaryString);
  2270. }
  2271. isEqual(t) {
  2272. return this.binaryString === t.binaryString;
  2273. }
  2274. }
  2275. Qt.EMPTY_BYTE_STRING = new Qt("");
  2276. const jt = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
  2277. /**
  2278. * Converts the possible Proto values for a timestamp value into a "seconds and
  2279. * nanos" representation.
  2280. */ function Wt(t) {
  2281. // The json interface (for the browser) will return an iso timestamp string,
  2282. // while the proto js library (for node) will return a
  2283. // google.protobuf.Timestamp instance.
  2284. if (M(!!t), "string" == typeof t) {
  2285. // The date string can have higher precision (nanos) than the Date class
  2286. // (millis), so we do some custom parsing here.
  2287. // Parse the nanos right out of the string.
  2288. let e = 0;
  2289. const n = jt.exec(t);
  2290. if (M(!!n), n[1]) {
  2291. // Pad the fraction out to 9 digits (nanos).
  2292. let t = n[1];
  2293. t = (t + "000000000").substr(0, 9), e = Number(t);
  2294. }
  2295. // Parse the date to get the seconds.
  2296. const s = new Date(t);
  2297. return {
  2298. seconds: Math.floor(s.getTime() / 1e3),
  2299. nanos: e
  2300. };
  2301. }
  2302. return {
  2303. seconds: zt(t.seconds),
  2304. nanos: zt(t.nanos)
  2305. };
  2306. }
  2307. /**
  2308. * Converts the possible Proto types for numbers into a JavaScript number.
  2309. * Returns 0 if the value is not numeric.
  2310. */ function zt(t) {
  2311. // TODO(bjornick): Handle int64 greater than 53 bits.
  2312. return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0;
  2313. }
  2314. /** Converts the possible Proto types for Blobs into a ByteString. */ function Ht(t) {
  2315. return "string" == typeof t ? Qt.fromBase64String(t) : Qt.fromUint8Array(t);
  2316. }
  2317. /**
  2318. * @license
  2319. * Copyright 2020 Google LLC
  2320. *
  2321. * Licensed under the Apache License, Version 2.0 (the "License");
  2322. * you may not use this file except in compliance with the License.
  2323. * You may obtain a copy of the License at
  2324. *
  2325. * http://www.apache.org/licenses/LICENSE-2.0
  2326. *
  2327. * Unless required by applicable law or agreed to in writing, software
  2328. * distributed under the License is distributed on an "AS IS" BASIS,
  2329. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2330. * See the License for the specific language governing permissions and
  2331. * limitations under the License.
  2332. */
  2333. /**
  2334. * Represents a locally-applied ServerTimestamp.
  2335. *
  2336. * Server Timestamps are backed by MapValues that contain an internal field
  2337. * `__type__` with a value of `server_timestamp`. The previous value and local
  2338. * write time are stored in its `__previous_value__` and `__local_write_time__`
  2339. * fields respectively.
  2340. *
  2341. * Notes:
  2342. * - ServerTimestampValue instances are created as the result of applying a
  2343. * transform. They can only exist in the local view of a document. Therefore
  2344. * they do not need to be parsed or serialized.
  2345. * - When evaluated locally (e.g. for snapshot.data()), they by default
  2346. * evaluate to `null`. This behavior can be configured by passing custom
  2347. * FieldValueOptions to value().
  2348. * - With respect to other ServerTimestampValues, they sort by their
  2349. * localWriteTime.
  2350. */ function Jt(t) {
  2351. var e, n;
  2352. 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);
  2353. }
  2354. /**
  2355. * Creates a new ServerTimestamp proto value (using the internal format).
  2356. */
  2357. /**
  2358. * Returns the value of the field before this ServerTimestamp was set.
  2359. *
  2360. * Preserving the previous values allows the user to display the last resoled
  2361. * value until the backend responds with the timestamp.
  2362. */
  2363. function Yt(t) {
  2364. const e = t.mapValue.fields.__previous_value__;
  2365. return Jt(e) ? Yt(e) : e;
  2366. }
  2367. /**
  2368. * Returns the local time at which this timestamp was first set.
  2369. */ function Xt(t) {
  2370. const e = Wt(t.mapValue.fields.__local_write_time__.timestampValue);
  2371. return new nt(e.seconds, e.nanos);
  2372. }
  2373. /**
  2374. * @license
  2375. * Copyright 2020 Google LLC
  2376. *
  2377. * Licensed under the Apache License, Version 2.0 (the "License");
  2378. * you may not use this file except in compliance with the License.
  2379. * You may obtain a copy of the License at
  2380. *
  2381. * http://www.apache.org/licenses/LICENSE-2.0
  2382. *
  2383. * Unless required by applicable law or agreed to in writing, software
  2384. * distributed under the License is distributed on an "AS IS" BASIS,
  2385. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2386. * See the License for the specific language governing permissions and
  2387. * limitations under the License.
  2388. */ const Zt = {
  2389. mapValue: {
  2390. fields: {
  2391. __type__: {
  2392. stringValue: "__max__"
  2393. }
  2394. }
  2395. }
  2396. }, te = {
  2397. nullValue: "NULL_VALUE"
  2398. };
  2399. /** Extracts the backend's type order for the provided value. */
  2400. function ee(t) {
  2401. 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 ? Jt(t) ? 4 /* TypeOrder.ServerTimestampValue */ : we(t) ? 9007199254740991 /* TypeOrder.MaxValue */ : 10 /* TypeOrder.ObjectValue */ : O();
  2402. }
  2403. /** Tests `left` and `right` for equality based on the backend semantics. */ function ne(t, e) {
  2404. if (t === e) return !0;
  2405. const n = ee(t);
  2406. if (n !== ee(e)) return !1;
  2407. switch (n) {
  2408. case 0 /* TypeOrder.NullValue */ :
  2409. case 9007199254740991 /* TypeOrder.MaxValue */ :
  2410. return !0;
  2411. case 1 /* TypeOrder.BooleanValue */ :
  2412. return t.booleanValue === e.booleanValue;
  2413. case 4 /* TypeOrder.ServerTimestampValue */ :
  2414. return Xt(t).isEqual(Xt(e));
  2415. case 3 /* TypeOrder.TimestampValue */ :
  2416. return function(t, e) {
  2417. if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length)
  2418. // Use string equality for ISO 8601 timestamps
  2419. return t.timestampValue === e.timestampValue;
  2420. const n = Wt(t.timestampValue), s = Wt(e.timestampValue);
  2421. return n.seconds === s.seconds && n.nanos === s.nanos;
  2422. }(t, e);
  2423. case 5 /* TypeOrder.StringValue */ :
  2424. return t.stringValue === e.stringValue;
  2425. case 6 /* TypeOrder.BlobValue */ :
  2426. return function(t, e) {
  2427. return Ht(t.bytesValue).isEqual(Ht(e.bytesValue));
  2428. }(t, e);
  2429. case 7 /* TypeOrder.RefValue */ :
  2430. return t.referenceValue === e.referenceValue;
  2431. case 8 /* TypeOrder.GeoPointValue */ :
  2432. return function(t, e) {
  2433. return zt(t.geoPointValue.latitude) === zt(e.geoPointValue.latitude) && zt(t.geoPointValue.longitude) === zt(e.geoPointValue.longitude);
  2434. }(t, e);
  2435. case 2 /* TypeOrder.NumberValue */ :
  2436. return function(t, e) {
  2437. if ("integerValue" in t && "integerValue" in e) return zt(t.integerValue) === zt(e.integerValue);
  2438. if ("doubleValue" in t && "doubleValue" in e) {
  2439. const n = zt(t.doubleValue), s = zt(e.doubleValue);
  2440. return n === s ? Ut(n) === Ut(s) : isNaN(n) && isNaN(s);
  2441. }
  2442. return !1;
  2443. }(t, e);
  2444. case 9 /* TypeOrder.ArrayValue */ :
  2445. return tt(t.arrayValue.values || [], e.arrayValue.values || [], ne);
  2446. case 10 /* TypeOrder.ObjectValue */ :
  2447. return function(t, e) {
  2448. const n = t.mapValue.fields || {}, s = e.mapValue.fields || {};
  2449. if ($t(n) !== $t(s)) return !1;
  2450. for (const t in n) if (n.hasOwnProperty(t) && (void 0 === s[t] || !ne(n[t], s[t]))) return !1;
  2451. return !0;
  2452. }
  2453. /** Returns true if the ArrayValue contains the specified element. */ (t, e);
  2454. default:
  2455. return O();
  2456. }
  2457. }
  2458. function se(t, e) {
  2459. return void 0 !== (t.values || []).find((t => ne(t, e)));
  2460. }
  2461. function ie(t, e) {
  2462. if (t === e) return 0;
  2463. const n = ee(t), s = ee(e);
  2464. if (n !== s) return Z(n, s);
  2465. switch (n) {
  2466. case 0 /* TypeOrder.NullValue */ :
  2467. case 9007199254740991 /* TypeOrder.MaxValue */ :
  2468. return 0;
  2469. case 1 /* TypeOrder.BooleanValue */ :
  2470. return Z(t.booleanValue, e.booleanValue);
  2471. case 2 /* TypeOrder.NumberValue */ :
  2472. return function(t, e) {
  2473. const n = zt(t.integerValue || t.doubleValue), s = zt(e.integerValue || e.doubleValue);
  2474. return n < s ? -1 : n > s ? 1 : n === s ? 0 :
  2475. // one or both are NaN.
  2476. isNaN(n) ? isNaN(s) ? 0 : -1 : 1;
  2477. }(t, e);
  2478. case 3 /* TypeOrder.TimestampValue */ :
  2479. return re(t.timestampValue, e.timestampValue);
  2480. case 4 /* TypeOrder.ServerTimestampValue */ :
  2481. return re(Xt(t), Xt(e));
  2482. case 5 /* TypeOrder.StringValue */ :
  2483. return Z(t.stringValue, e.stringValue);
  2484. case 6 /* TypeOrder.BlobValue */ :
  2485. return function(t, e) {
  2486. const n = Ht(t), s = Ht(e);
  2487. return n.compareTo(s);
  2488. }(t.bytesValue, e.bytesValue);
  2489. case 7 /* TypeOrder.RefValue */ :
  2490. return function(t, e) {
  2491. const n = t.split("/"), s = e.split("/");
  2492. for (let t = 0; t < n.length && t < s.length; t++) {
  2493. const e = Z(n[t], s[t]);
  2494. if (0 !== e) return e;
  2495. }
  2496. return Z(n.length, s.length);
  2497. }(t.referenceValue, e.referenceValue);
  2498. case 8 /* TypeOrder.GeoPointValue */ :
  2499. return function(t, e) {
  2500. const n = Z(zt(t.latitude), zt(e.latitude));
  2501. if (0 !== n) return n;
  2502. return Z(zt(t.longitude), zt(e.longitude));
  2503. }(t.geoPointValue, e.geoPointValue);
  2504. case 9 /* TypeOrder.ArrayValue */ :
  2505. return function(t, e) {
  2506. const n = t.values || [], s = e.values || [];
  2507. for (let t = 0; t < n.length && t < s.length; ++t) {
  2508. const e = ie(n[t], s[t]);
  2509. if (e) return e;
  2510. }
  2511. return Z(n.length, s.length);
  2512. }(t.arrayValue, e.arrayValue);
  2513. case 10 /* TypeOrder.ObjectValue */ :
  2514. return function(t, e) {
  2515. if (t === Zt.mapValue && e === Zt.mapValue) return 0;
  2516. if (t === Zt.mapValue) return 1;
  2517. if (e === Zt.mapValue) return -1;
  2518. const n = t.fields || {}, s = Object.keys(n), i = e.fields || {}, r = Object.keys(i);
  2519. // Even though MapValues are likely sorted correctly based on their insertion
  2520. // order (e.g. when received from the backend), local modifications can bring
  2521. // elements out of order. We need to re-sort the elements to ensure that
  2522. // canonical IDs are independent of insertion order.
  2523. s.sort(), r.sort();
  2524. for (let t = 0; t < s.length && t < r.length; ++t) {
  2525. const e = Z(s[t], r[t]);
  2526. if (0 !== e) return e;
  2527. const o = ie(n[s[t]], i[r[t]]);
  2528. if (0 !== o) return o;
  2529. }
  2530. return Z(s.length, r.length);
  2531. }
  2532. /**
  2533. * Generates the canonical ID for the provided field value (as used in Target
  2534. * serialization).
  2535. */ (t.mapValue, e.mapValue);
  2536. default:
  2537. throw O();
  2538. }
  2539. }
  2540. function re(t, e) {
  2541. if ("string" == typeof t && "string" == typeof e && t.length === e.length) return Z(t, e);
  2542. const n = Wt(t), s = Wt(e), i = Z(n.seconds, s.seconds);
  2543. return 0 !== i ? i : Z(n.nanos, s.nanos);
  2544. }
  2545. function oe(t) {
  2546. return ue(t);
  2547. }
  2548. function ue(t) {
  2549. 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) {
  2550. const e = Wt(t);
  2551. return `time(${e.seconds},${e.nanos})`;
  2552. }(t.timestampValue) : "stringValue" in t ? t.stringValue : "bytesValue" in t ? Ht(t.bytesValue).toBase64() : "referenceValue" in t ? (n = t.referenceValue,
  2553. ct.fromName(n).toString()) : "geoPointValue" in t ? `geo(${(e = t.geoPointValue).latitude},${e.longitude})` : "arrayValue" in t ? function(t) {
  2554. let e = "[", n = !0;
  2555. for (const s of t.values || []) n ? n = !1 : e += ",", e += ue(s);
  2556. return e + "]";
  2557. }
  2558. /** Returns a reference value for the provided database and key. */ (t.arrayValue) : "mapValue" in t ? function(t) {
  2559. // Iteration order in JavaScript is not guaranteed. To ensure that we generate
  2560. // matching canonical IDs for identical maps, we need to sort the keys.
  2561. const e = Object.keys(t.fields || {}).sort();
  2562. let n = "{", s = !0;
  2563. for (const i of e) s ? s = !1 : n += ",", n += `${i}:${ue(t.fields[i])}`;
  2564. return n + "}";
  2565. }(t.mapValue) : O();
  2566. var e, n;
  2567. }
  2568. function ce(t, e) {
  2569. return {
  2570. referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`
  2571. };
  2572. }
  2573. /** Returns true if `value` is an IntegerValue . */ function ae(t) {
  2574. return !!t && "integerValue" in t;
  2575. }
  2576. /** Returns true if `value` is a DoubleValue. */
  2577. /** Returns true if `value` is an ArrayValue. */
  2578. function he(t) {
  2579. return !!t && "arrayValue" in t;
  2580. }
  2581. /** Returns true if `value` is a NullValue. */ function le(t) {
  2582. return !!t && "nullValue" in t;
  2583. }
  2584. /** Returns true if `value` is NaN. */ function fe(t) {
  2585. return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue));
  2586. }
  2587. /** Returns true if `value` is a MapValue. */ function de(t) {
  2588. return !!t && "mapValue" in t;
  2589. }
  2590. /** Creates a deep copy of `source`. */ function _e(t) {
  2591. if (t.geoPointValue) return {
  2592. geoPointValue: Object.assign({}, t.geoPointValue)
  2593. };
  2594. if (t.timestampValue && "object" == typeof t.timestampValue) return {
  2595. timestampValue: Object.assign({}, t.timestampValue)
  2596. };
  2597. if (t.mapValue) {
  2598. const e = {
  2599. mapValue: {
  2600. fields: {}
  2601. }
  2602. };
  2603. return Bt(t.mapValue.fields, ((t, n) => e.mapValue.fields[t] = _e(n))), e;
  2604. }
  2605. if (t.arrayValue) {
  2606. const e = {
  2607. arrayValue: {
  2608. values: []
  2609. }
  2610. };
  2611. for (let n = 0; n < (t.arrayValue.values || []).length; ++n) e.arrayValue.values[n] = _e(t.arrayValue.values[n]);
  2612. return e;
  2613. }
  2614. return Object.assign({}, t);
  2615. }
  2616. /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function we(t) {
  2617. return "__max__" === (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue;
  2618. }
  2619. /** Returns the lowest value for the given value type (inclusive). */ function me(t) {
  2620. return "nullValue" in t ? te : "booleanValue" in t ? {
  2621. booleanValue: !1
  2622. } : "integerValue" in t || "doubleValue" in t ? {
  2623. doubleValue: NaN
  2624. } : "timestampValue" in t ? {
  2625. timestampValue: {
  2626. seconds: Number.MIN_SAFE_INTEGER
  2627. }
  2628. } : "stringValue" in t ? {
  2629. stringValue: ""
  2630. } : "bytesValue" in t ? {
  2631. bytesValue: ""
  2632. } : "referenceValue" in t ? ce(Ft.empty(), ct.empty()) : "geoPointValue" in t ? {
  2633. geoPointValue: {
  2634. latitude: -90,
  2635. longitude: -180
  2636. }
  2637. } : "arrayValue" in t ? {
  2638. arrayValue: {}
  2639. } : "mapValue" in t ? {
  2640. mapValue: {}
  2641. } : O();
  2642. }
  2643. /** Returns the largest value for the given value type (exclusive). */ function ge(t) {
  2644. return "nullValue" in t ? {
  2645. booleanValue: !1
  2646. } : "booleanValue" in t ? {
  2647. doubleValue: NaN
  2648. } : "integerValue" in t || "doubleValue" in t ? {
  2649. timestampValue: {
  2650. seconds: Number.MIN_SAFE_INTEGER
  2651. }
  2652. } : "timestampValue" in t ? {
  2653. stringValue: ""
  2654. } : "stringValue" in t ? {
  2655. bytesValue: ""
  2656. } : "bytesValue" in t ? ce(Ft.empty(), ct.empty()) : "referenceValue" in t ? {
  2657. geoPointValue: {
  2658. latitude: -90,
  2659. longitude: -180
  2660. }
  2661. } : "geoPointValue" in t ? {
  2662. arrayValue: {}
  2663. } : "arrayValue" in t ? {
  2664. mapValue: {}
  2665. } : "mapValue" in t ? Zt : O();
  2666. }
  2667. function ye(t, e) {
  2668. const n = ie(t.value, e.value);
  2669. return 0 !== n ? n : t.inclusive && !e.inclusive ? -1 : !t.inclusive && e.inclusive ? 1 : 0;
  2670. }
  2671. function pe(t, e) {
  2672. const n = ie(t.value, e.value);
  2673. return 0 !== n ? n : t.inclusive && !e.inclusive ? 1 : !t.inclusive && e.inclusive ? -1 : 0;
  2674. }
  2675. /**
  2676. * @license
  2677. * Copyright 2022 Google LLC
  2678. *
  2679. * Licensed under the Apache License, Version 2.0 (the "License");
  2680. * you may not use this file except in compliance with the License.
  2681. * You may obtain a copy of the License at
  2682. *
  2683. * http://www.apache.org/licenses/LICENSE-2.0
  2684. *
  2685. * Unless required by applicable law or agreed to in writing, software
  2686. * distributed under the License is distributed on an "AS IS" BASIS,
  2687. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2688. * See the License for the specific language governing permissions and
  2689. * limitations under the License.
  2690. */
  2691. /**
  2692. * Represents a bound of a query.
  2693. *
  2694. * The bound is specified with the given components representing a position and
  2695. * whether it's just before or just after the position (relative to whatever the
  2696. * query order is).
  2697. *
  2698. * The position represents a logical index position for a query. It's a prefix
  2699. * of values for the (potentially implicit) order by clauses of a query.
  2700. *
  2701. * Bound provides a function to determine whether a document comes before or
  2702. * after a bound. This is influenced by whether the position is just before or
  2703. * just after the provided values.
  2704. */ class Ie {
  2705. constructor(t, e) {
  2706. this.position = t, this.inclusive = e;
  2707. }
  2708. }
  2709. function Te(t, e, n) {
  2710. let s = 0;
  2711. for (let i = 0; i < t.position.length; i++) {
  2712. const r = e[i], o = t.position[i];
  2713. if (r.field.isKeyField()) s = ct.comparator(ct.fromName(o.referenceValue), n.key); else {
  2714. s = ie(o, n.data.field(r.field));
  2715. }
  2716. if ("desc" /* Direction.DESCENDING */ === r.dir && (s *= -1), 0 !== s) break;
  2717. }
  2718. return s;
  2719. }
  2720. /**
  2721. * Returns true if a document sorts after a bound using the provided sort
  2722. * order.
  2723. */ function Ee(t, e) {
  2724. if (null === t) return null === e;
  2725. if (null === e) return !1;
  2726. if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1;
  2727. for (let n = 0; n < t.position.length; n++) {
  2728. if (!ne(t.position[n], e.position[n])) return !1;
  2729. }
  2730. return !0;
  2731. }
  2732. /**
  2733. * @license
  2734. * Copyright 2022 Google LLC
  2735. *
  2736. * Licensed under the Apache License, Version 2.0 (the "License");
  2737. * you may not use this file except in compliance with the License.
  2738. * You may obtain a copy of the License at
  2739. *
  2740. * http://www.apache.org/licenses/LICENSE-2.0
  2741. *
  2742. * Unless required by applicable law or agreed to in writing, software
  2743. * distributed under the License is distributed on an "AS IS" BASIS,
  2744. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2745. * See the License for the specific language governing permissions and
  2746. * limitations under the License.
  2747. */ class Ae {}
  2748. class Re extends Ae {
  2749. constructor(t, e, n) {
  2750. super(), this.field = t, this.op = e, this.value = n;
  2751. }
  2752. /**
  2753. * Creates a filter based on the provided arguments.
  2754. */ static create(t, e, n) {
  2755. return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, n) : new ke(t, e, n) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new $e(t, n) : "in" /* Operator.IN */ === e ? new Be(t, n) : "not-in" /* Operator.NOT_IN */ === e ? new Le(t, n) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new qe(t, n) : new Re(t, e, n);
  2756. }
  2757. static createKeyFieldInFilter(t, e, n) {
  2758. return "in" /* Operator.IN */ === e ? new Oe(t, n) : new Me(t, n);
  2759. }
  2760. matches(t) {
  2761. const e = t.data.field(this.field);
  2762. // Types do not have to match in NOT_EQUAL filters.
  2763. return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && this.matchesComparison(ie(e, this.value)) : null !== e && ee(this.value) === ee(e) && this.matchesComparison(ie(e, this.value));
  2764. // Only compare types with matching backend order (such as double and int).
  2765. }
  2766. matchesComparison(t) {
  2767. switch (this.op) {
  2768. case "<" /* Operator.LESS_THAN */ :
  2769. return t < 0;
  2770. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  2771. return t <= 0;
  2772. case "==" /* Operator.EQUAL */ :
  2773. return 0 === t;
  2774. case "!=" /* Operator.NOT_EQUAL */ :
  2775. return 0 !== t;
  2776. case ">" /* Operator.GREATER_THAN */ :
  2777. return t > 0;
  2778. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  2779. return t >= 0;
  2780. default:
  2781. return O();
  2782. }
  2783. }
  2784. isInequality() {
  2785. 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;
  2786. }
  2787. getFlattenedFilters() {
  2788. return [ this ];
  2789. }
  2790. getFilters() {
  2791. return [ this ];
  2792. }
  2793. getFirstInequalityField() {
  2794. return this.isInequality() ? this.field : null;
  2795. }
  2796. }
  2797. class be extends Ae {
  2798. constructor(t, e) {
  2799. super(), this.filters = t, this.op = e, this.ht = null;
  2800. }
  2801. /**
  2802. * Creates a filter based on the provided arguments.
  2803. */ static create(t, e) {
  2804. return new be(t, e);
  2805. }
  2806. matches(t) {
  2807. return Pe(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t)));
  2808. }
  2809. getFlattenedFilters() {
  2810. return null !== this.ht || (this.ht = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])),
  2811. this.ht;
  2812. }
  2813. // Returns a mutable copy of `this.filters`
  2814. getFilters() {
  2815. return Object.assign([], this.filters);
  2816. }
  2817. getFirstInequalityField() {
  2818. const t = this.lt((t => t.isInequality()));
  2819. return null !== t ? t.field : null;
  2820. }
  2821. // Performs a depth-first search to find and return the first FieldFilter in the composite filter
  2822. // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the
  2823. // predicate.
  2824. lt(t) {
  2825. for (const e of this.getFlattenedFilters()) if (t(e)) return e;
  2826. return null;
  2827. }
  2828. }
  2829. function Pe(t) {
  2830. return "and" /* CompositeOperator.AND */ === t.op;
  2831. }
  2832. function ve(t) {
  2833. return "or" /* CompositeOperator.OR */ === t.op;
  2834. }
  2835. /**
  2836. * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.
  2837. */ function Ve(t) {
  2838. return Se(t) && Pe(t);
  2839. }
  2840. /**
  2841. * Returns true if this filter does not contain any composite filters. Returns false otherwise.
  2842. */ function Se(t) {
  2843. for (const e of t.filters) if (e instanceof be) return !1;
  2844. return !0;
  2845. }
  2846. function De(t) {
  2847. if (t instanceof Re)
  2848. // TODO(b/29183165): Technically, this won't be unique if two values have
  2849. // the same description, such as the int 3 and the string "3". So we should
  2850. // add the types in here somehow, too.
  2851. return t.field.canonicalString() + t.op.toString() + oe(t.value);
  2852. if (Ve(t))
  2853. // Older SDK versions use an implicit AND operation between their filters.
  2854. // In the new SDK versions, the developer may use an explicit AND filter.
  2855. // To stay consistent with the old usages, we add a special case to ensure
  2856. // the canonical ID for these two are the same. For example:
  2857. // `col.whereEquals("a", 1).whereEquals("b", 2)` should have the same
  2858. // canonical ID as `col.where(and(equals("a",1), equals("b",2)))`.
  2859. return t.filters.map((t => De(t))).join(",");
  2860. {
  2861. // filter instanceof CompositeFilter
  2862. const e = t.filters.map((t => De(t))).join(",");
  2863. return `${t.op}(${e})`;
  2864. }
  2865. }
  2866. function Ce(t, e) {
  2867. return t instanceof Re ? function(t, e) {
  2868. return e instanceof Re && t.op === e.op && t.field.isEqual(e.field) && ne(t.value, e.value);
  2869. }(t, e) : t instanceof be ? function(t, e) {
  2870. if (e instanceof be && t.op === e.op && t.filters.length === e.filters.length) {
  2871. return t.filters.reduce(((t, n, s) => t && Ce(n, e.filters[s])), !0);
  2872. }
  2873. return !1;
  2874. }
  2875. /**
  2876. * Returns a new composite filter that contains all filter from
  2877. * `compositeFilter` plus all the given filters in `otherFilters`.
  2878. */ (t, e) : void O();
  2879. }
  2880. function xe(t, e) {
  2881. const n = t.filters.concat(e);
  2882. return be.create(n, t.op);
  2883. }
  2884. /** Returns a debug description for `filter`. */ function Ne(t) {
  2885. return t instanceof Re ? function(t) {
  2886. return `${t.field.canonicalString()} ${t.op} ${oe(t.value)}`;
  2887. }
  2888. /** Filter that matches on key fields (i.e. '__name__'). */ (t) : t instanceof be ? function(t) {
  2889. return t.op.toString() + " {" + t.getFilters().map(Ne).join(" ,") + "}";
  2890. }(t) : "Filter";
  2891. }
  2892. class ke extends Re {
  2893. constructor(t, e, n) {
  2894. super(t, e, n), this.key = ct.fromName(n.referenceValue);
  2895. }
  2896. matches(t) {
  2897. const e = ct.comparator(t.key, this.key);
  2898. return this.matchesComparison(e);
  2899. }
  2900. }
  2901. /** Filter that matches on key fields within an array. */ class Oe extends Re {
  2902. constructor(t, e) {
  2903. super(t, "in" /* Operator.IN */ , e), this.keys = Fe("in" /* Operator.IN */ , e);
  2904. }
  2905. matches(t) {
  2906. return this.keys.some((e => e.isEqual(t.key)));
  2907. }
  2908. }
  2909. /** Filter that matches on key fields not present within an array. */ class Me extends Re {
  2910. constructor(t, e) {
  2911. super(t, "not-in" /* Operator.NOT_IN */ , e), this.keys = Fe("not-in" /* Operator.NOT_IN */ , e);
  2912. }
  2913. matches(t) {
  2914. return !this.keys.some((e => e.isEqual(t.key)));
  2915. }
  2916. }
  2917. function Fe(t, e) {
  2918. var n;
  2919. return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((t => ct.fromName(t.referenceValue)));
  2920. }
  2921. /** A Filter that implements the array-contains operator. */ class $e extends Re {
  2922. constructor(t, e) {
  2923. super(t, "array-contains" /* Operator.ARRAY_CONTAINS */ , e);
  2924. }
  2925. matches(t) {
  2926. const e = t.data.field(this.field);
  2927. return he(e) && se(e.arrayValue, this.value);
  2928. }
  2929. }
  2930. /** A Filter that implements the IN operator. */ class Be extends Re {
  2931. constructor(t, e) {
  2932. super(t, "in" /* Operator.IN */ , e);
  2933. }
  2934. matches(t) {
  2935. const e = t.data.field(this.field);
  2936. return null !== e && se(this.value.arrayValue, e);
  2937. }
  2938. }
  2939. /** A Filter that implements the not-in operator. */ class Le extends Re {
  2940. constructor(t, e) {
  2941. super(t, "not-in" /* Operator.NOT_IN */ , e);
  2942. }
  2943. matches(t) {
  2944. if (se(this.value.arrayValue, {
  2945. nullValue: "NULL_VALUE"
  2946. })) return !1;
  2947. const e = t.data.field(this.field);
  2948. return null !== e && !se(this.value.arrayValue, e);
  2949. }
  2950. }
  2951. /** A Filter that implements the array-contains-any operator. */ class qe extends Re {
  2952. constructor(t, e) {
  2953. super(t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , e);
  2954. }
  2955. matches(t) {
  2956. const e = t.data.field(this.field);
  2957. return !(!he(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => se(this.value.arrayValue, t)));
  2958. }
  2959. }
  2960. /**
  2961. * @license
  2962. * Copyright 2022 Google LLC
  2963. *
  2964. * Licensed under the Apache License, Version 2.0 (the "License");
  2965. * you may not use this file except in compliance with the License.
  2966. * You may obtain a copy of the License at
  2967. *
  2968. * http://www.apache.org/licenses/LICENSE-2.0
  2969. *
  2970. * Unless required by applicable law or agreed to in writing, software
  2971. * distributed under the License is distributed on an "AS IS" BASIS,
  2972. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2973. * See the License for the specific language governing permissions and
  2974. * limitations under the License.
  2975. */
  2976. /**
  2977. * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
  2978. */ class Ue {
  2979. constructor(t, e = "asc" /* Direction.ASCENDING */) {
  2980. this.field = t, this.dir = e;
  2981. }
  2982. }
  2983. function Ke(t, e) {
  2984. return t.dir === e.dir && t.field.isEqual(e.field);
  2985. }
  2986. /**
  2987. * @license
  2988. * Copyright 2017 Google LLC
  2989. *
  2990. * Licensed under the Apache License, Version 2.0 (the "License");
  2991. * you may not use this file except in compliance with the License.
  2992. * You may obtain a copy of the License at
  2993. *
  2994. * http://www.apache.org/licenses/LICENSE-2.0
  2995. *
  2996. * Unless required by applicable law or agreed to in writing, software
  2997. * distributed under the License is distributed on an "AS IS" BASIS,
  2998. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2999. * See the License for the specific language governing permissions and
  3000. * limitations under the License.
  3001. */
  3002. // An immutable sorted map implementation, based on a Left-leaning Red-Black
  3003. // tree.
  3004. class Ge {
  3005. constructor(t, e) {
  3006. this.comparator = t, this.root = e || je.EMPTY;
  3007. }
  3008. // Returns a copy of the map, with the specified key/value added or replaced.
  3009. insert(t, e) {
  3010. return new Ge(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, je.BLACK, null, null));
  3011. }
  3012. // Returns a copy of the map, with the specified key removed.
  3013. remove(t) {
  3014. return new Ge(this.comparator, this.root.remove(t, this.comparator).copy(null, null, je.BLACK, null, null));
  3015. }
  3016. // Returns the value of the node with the given key, or null.
  3017. get(t) {
  3018. let e = this.root;
  3019. for (;!e.isEmpty(); ) {
  3020. const n = this.comparator(t, e.key);
  3021. if (0 === n) return e.value;
  3022. n < 0 ? e = e.left : n > 0 && (e = e.right);
  3023. }
  3024. return null;
  3025. }
  3026. // Returns the index of the element in this sorted map, or -1 if it doesn't
  3027. // exist.
  3028. indexOf(t) {
  3029. // Number of nodes that were pruned when descending right
  3030. let e = 0, n = this.root;
  3031. for (;!n.isEmpty(); ) {
  3032. const s = this.comparator(t, n.key);
  3033. if (0 === s) return e + n.left.size;
  3034. s < 0 ? n = n.left : (
  3035. // Count all nodes left of the node plus the node itself
  3036. e += n.left.size + 1, n = n.right);
  3037. }
  3038. // Node not found
  3039. return -1;
  3040. }
  3041. isEmpty() {
  3042. return this.root.isEmpty();
  3043. }
  3044. // Returns the total number of nodes in the map.
  3045. get size() {
  3046. return this.root.size;
  3047. }
  3048. // Returns the minimum key in the map.
  3049. minKey() {
  3050. return this.root.minKey();
  3051. }
  3052. // Returns the maximum key in the map.
  3053. maxKey() {
  3054. return this.root.maxKey();
  3055. }
  3056. // Traverses the map in key order and calls the specified action function
  3057. // for each key/value pair. If action returns true, traversal is aborted.
  3058. // Returns the first truthy value returned by action, or the last falsey
  3059. // value returned by action.
  3060. inorderTraversal(t) {
  3061. return this.root.inorderTraversal(t);
  3062. }
  3063. forEach(t) {
  3064. this.inorderTraversal(((e, n) => (t(e, n), !1)));
  3065. }
  3066. toString() {
  3067. const t = [];
  3068. return this.inorderTraversal(((e, n) => (t.push(`${e}:${n}`), !1))), `{${t.join(", ")}}`;
  3069. }
  3070. // Traverses the map in reverse key order and calls the specified action
  3071. // function for each key/value pair. If action returns true, traversal is
  3072. // aborted.
  3073. // Returns the first truthy value returned by action, or the last falsey
  3074. // value returned by action.
  3075. reverseTraversal(t) {
  3076. return this.root.reverseTraversal(t);
  3077. }
  3078. // Returns an iterator over the SortedMap.
  3079. getIterator() {
  3080. return new Qe(this.root, null, this.comparator, !1);
  3081. }
  3082. getIteratorFrom(t) {
  3083. return new Qe(this.root, t, this.comparator, !1);
  3084. }
  3085. getReverseIterator() {
  3086. return new Qe(this.root, null, this.comparator, !0);
  3087. }
  3088. getReverseIteratorFrom(t) {
  3089. return new Qe(this.root, t, this.comparator, !0);
  3090. }
  3091. }
  3092. // end SortedMap
  3093. // An iterator over an LLRBNode.
  3094. class Qe {
  3095. constructor(t, e, n, s) {
  3096. this.isReverse = s, this.nodeStack = [];
  3097. let i = 1;
  3098. for (;!t.isEmpty(); ) if (i = e ? n(t.key, e) : 1,
  3099. // flip the comparison if we're going in reverse
  3100. e && s && (i *= -1), i < 0)
  3101. // This node is less than our start key. ignore it
  3102. t = this.isReverse ? t.left : t.right; else {
  3103. if (0 === i) {
  3104. // This node is exactly equal to our start key. Push it on the stack,
  3105. // but stop iterating;
  3106. this.nodeStack.push(t);
  3107. break;
  3108. }
  3109. // This node is greater than our start key, add it to the stack and move
  3110. // to the next one
  3111. this.nodeStack.push(t), t = this.isReverse ? t.right : t.left;
  3112. }
  3113. }
  3114. getNext() {
  3115. let t = this.nodeStack.pop();
  3116. const e = {
  3117. key: t.key,
  3118. value: t.value
  3119. };
  3120. 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),
  3121. t = t.left;
  3122. return e;
  3123. }
  3124. hasNext() {
  3125. return this.nodeStack.length > 0;
  3126. }
  3127. peek() {
  3128. if (0 === this.nodeStack.length) return null;
  3129. const t = this.nodeStack[this.nodeStack.length - 1];
  3130. return {
  3131. key: t.key,
  3132. value: t.value
  3133. };
  3134. }
  3135. }
  3136. // end SortedMapIterator
  3137. // Represents a node in a Left-leaning Red-Black tree.
  3138. class je {
  3139. constructor(t, e, n, s, i) {
  3140. this.key = t, this.value = e, this.color = null != n ? n : je.RED, this.left = null != s ? s : je.EMPTY,
  3141. this.right = null != i ? i : je.EMPTY, this.size = this.left.size + 1 + this.right.size;
  3142. }
  3143. // Returns a copy of the current node, optionally replacing pieces of it.
  3144. copy(t, e, n, s, i) {
  3145. return new je(null != t ? t : this.key, null != e ? e : this.value, null != n ? n : this.color, null != s ? s : this.left, null != i ? i : this.right);
  3146. }
  3147. isEmpty() {
  3148. return !1;
  3149. }
  3150. // Traverses the tree in key order and calls the specified action function
  3151. // for each node. If action returns true, traversal is aborted.
  3152. // Returns the first truthy value returned by action, or the last falsey
  3153. // value returned by action.
  3154. inorderTraversal(t) {
  3155. return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t);
  3156. }
  3157. // Traverses the tree in reverse key order and calls the specified action
  3158. // function for each node. If action returns true, traversal is aborted.
  3159. // Returns the first truthy value returned by action, or the last falsey
  3160. // value returned by action.
  3161. reverseTraversal(t) {
  3162. return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t);
  3163. }
  3164. // Returns the minimum node in the tree.
  3165. min() {
  3166. return this.left.isEmpty() ? this : this.left.min();
  3167. }
  3168. // Returns the maximum key in the tree.
  3169. minKey() {
  3170. return this.min().key;
  3171. }
  3172. // Returns the maximum key in the tree.
  3173. maxKey() {
  3174. return this.right.isEmpty() ? this.key : this.right.maxKey();
  3175. }
  3176. // Returns new tree, with the key/value added.
  3177. insert(t, e, n) {
  3178. let s = this;
  3179. const i = n(t, s.key);
  3180. return s = i < 0 ? s.copy(null, null, null, s.left.insert(t, e, n), null) : 0 === i ? s.copy(null, e, null, null, null) : s.copy(null, null, null, null, s.right.insert(t, e, n)),
  3181. s.fixUp();
  3182. }
  3183. removeMin() {
  3184. if (this.left.isEmpty()) return je.EMPTY;
  3185. let t = this;
  3186. return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null),
  3187. t.fixUp();
  3188. }
  3189. // Returns new tree, with the specified item removed.
  3190. remove(t, e) {
  3191. let n, s = this;
  3192. if (e(t, s.key) < 0) s.left.isEmpty() || s.left.isRed() || s.left.left.isRed() || (s = s.moveRedLeft()),
  3193. s = s.copy(null, null, null, s.left.remove(t, e), null); else {
  3194. if (s.left.isRed() && (s = s.rotateRight()), s.right.isEmpty() || s.right.isRed() || s.right.left.isRed() || (s = s.moveRedRight()),
  3195. 0 === e(t, s.key)) {
  3196. if (s.right.isEmpty()) return je.EMPTY;
  3197. n = s.right.min(), s = s.copy(n.key, n.value, null, null, s.right.removeMin());
  3198. }
  3199. s = s.copy(null, null, null, null, s.right.remove(t, e));
  3200. }
  3201. return s.fixUp();
  3202. }
  3203. isRed() {
  3204. return this.color;
  3205. }
  3206. // Returns new tree after performing any needed rotations.
  3207. fixUp() {
  3208. let t = this;
  3209. return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()),
  3210. t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t;
  3211. }
  3212. moveRedLeft() {
  3213. let t = this.colorFlip();
  3214. return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()),
  3215. t = t.rotateLeft(), t = t.colorFlip()), t;
  3216. }
  3217. moveRedRight() {
  3218. let t = this.colorFlip();
  3219. return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t;
  3220. }
  3221. rotateLeft() {
  3222. const t = this.copy(null, null, je.RED, null, this.right.left);
  3223. return this.right.copy(null, null, this.color, t, null);
  3224. }
  3225. rotateRight() {
  3226. const t = this.copy(null, null, je.RED, this.left.right, null);
  3227. return this.left.copy(null, null, this.color, null, t);
  3228. }
  3229. colorFlip() {
  3230. const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);
  3231. return this.copy(null, null, !this.color, t, e);
  3232. }
  3233. // For testing.
  3234. checkMaxDepth() {
  3235. const t = this.check();
  3236. return Math.pow(2, t) <= this.size + 1;
  3237. }
  3238. // In a balanced RB tree, the black-depth (number of black nodes) from root to
  3239. // leaves is equal on both sides. This function verifies that or asserts.
  3240. check() {
  3241. if (this.isRed() && this.left.isRed()) throw O();
  3242. if (this.right.isRed()) throw O();
  3243. const t = this.left.check();
  3244. if (t !== this.right.check()) throw O();
  3245. return t + (this.isRed() ? 0 : 1);
  3246. }
  3247. }
  3248. // end LLRBNode
  3249. // Empty node is shared between all LLRB trees.
  3250. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3251. je.EMPTY = null, je.RED = !0, je.BLACK = !1;
  3252. // end LLRBEmptyNode
  3253. je.EMPTY = new
  3254. // Represents an empty node (a leaf node in the Red-Black Tree).
  3255. class {
  3256. constructor() {
  3257. this.size = 0;
  3258. }
  3259. get key() {
  3260. throw O();
  3261. }
  3262. get value() {
  3263. throw O();
  3264. }
  3265. get color() {
  3266. throw O();
  3267. }
  3268. get left() {
  3269. throw O();
  3270. }
  3271. get right() {
  3272. throw O();
  3273. }
  3274. // Returns a copy of the current node.
  3275. copy(t, e, n, s, i) {
  3276. return this;
  3277. }
  3278. // Returns a copy of the tree, with the specified key/value added.
  3279. insert(t, e, n) {
  3280. return new je(t, e);
  3281. }
  3282. // Returns a copy of the tree, with the specified key removed.
  3283. remove(t, e) {
  3284. return this;
  3285. }
  3286. isEmpty() {
  3287. return !0;
  3288. }
  3289. inorderTraversal(t) {
  3290. return !1;
  3291. }
  3292. reverseTraversal(t) {
  3293. return !1;
  3294. }
  3295. minKey() {
  3296. return null;
  3297. }
  3298. maxKey() {
  3299. return null;
  3300. }
  3301. isRed() {
  3302. return !1;
  3303. }
  3304. // For testing.
  3305. checkMaxDepth() {
  3306. return !0;
  3307. }
  3308. check() {
  3309. return 0;
  3310. }
  3311. };
  3312. /**
  3313. * @license
  3314. * Copyright 2017 Google LLC
  3315. *
  3316. * Licensed under the Apache License, Version 2.0 (the "License");
  3317. * you may not use this file except in compliance with the License.
  3318. * You may obtain a copy of the License at
  3319. *
  3320. * http://www.apache.org/licenses/LICENSE-2.0
  3321. *
  3322. * Unless required by applicable law or agreed to in writing, software
  3323. * distributed under the License is distributed on an "AS IS" BASIS,
  3324. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3325. * See the License for the specific language governing permissions and
  3326. * limitations under the License.
  3327. */
  3328. /**
  3329. * SortedSet is an immutable (copy-on-write) collection that holds elements
  3330. * in order specified by the provided comparator.
  3331. *
  3332. * NOTE: if provided comparator returns 0 for two elements, we consider them to
  3333. * be equal!
  3334. */
  3335. class We {
  3336. constructor(t) {
  3337. this.comparator = t, this.data = new Ge(this.comparator);
  3338. }
  3339. has(t) {
  3340. return null !== this.data.get(t);
  3341. }
  3342. first() {
  3343. return this.data.minKey();
  3344. }
  3345. last() {
  3346. return this.data.maxKey();
  3347. }
  3348. get size() {
  3349. return this.data.size;
  3350. }
  3351. indexOf(t) {
  3352. return this.data.indexOf(t);
  3353. }
  3354. /** Iterates elements in order defined by "comparator" */ forEach(t) {
  3355. this.data.inorderTraversal(((e, n) => (t(e), !1)));
  3356. }
  3357. /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */ forEachInRange(t, e) {
  3358. const n = this.data.getIteratorFrom(t[0]);
  3359. for (;n.hasNext(); ) {
  3360. const s = n.getNext();
  3361. if (this.comparator(s.key, t[1]) >= 0) return;
  3362. e(s.key);
  3363. }
  3364. }
  3365. /**
  3366. * Iterates over `elem`s such that: start &lt;= elem until false is returned.
  3367. */ forEachWhile(t, e) {
  3368. let n;
  3369. for (n = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); n.hasNext(); ) {
  3370. if (!t(n.getNext().key)) return;
  3371. }
  3372. }
  3373. /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) {
  3374. const e = this.data.getIteratorFrom(t);
  3375. return e.hasNext() ? e.getNext().key : null;
  3376. }
  3377. getIterator() {
  3378. return new ze(this.data.getIterator());
  3379. }
  3380. getIteratorFrom(t) {
  3381. return new ze(this.data.getIteratorFrom(t));
  3382. }
  3383. /** Inserts or updates an element */ add(t) {
  3384. return this.copy(this.data.remove(t).insert(t, !0));
  3385. }
  3386. /** Deletes an element */ delete(t) {
  3387. return this.has(t) ? this.copy(this.data.remove(t)) : this;
  3388. }
  3389. isEmpty() {
  3390. return this.data.isEmpty();
  3391. }
  3392. unionWith(t) {
  3393. let e = this;
  3394. // Make sure `result` always refers to the larger one of the two sets.
  3395. return e.size < t.size && (e = t, t = this), t.forEach((t => {
  3396. e = e.add(t);
  3397. })), e;
  3398. }
  3399. isEqual(t) {
  3400. if (!(t instanceof We)) return !1;
  3401. if (this.size !== t.size) return !1;
  3402. const e = this.data.getIterator(), n = t.data.getIterator();
  3403. for (;e.hasNext(); ) {
  3404. const t = e.getNext().key, s = n.getNext().key;
  3405. if (0 !== this.comparator(t, s)) return !1;
  3406. }
  3407. return !0;
  3408. }
  3409. toArray() {
  3410. const t = [];
  3411. return this.forEach((e => {
  3412. t.push(e);
  3413. })), t;
  3414. }
  3415. toString() {
  3416. const t = [];
  3417. return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")";
  3418. }
  3419. copy(t) {
  3420. const e = new We(this.comparator);
  3421. return e.data = t, e;
  3422. }
  3423. }
  3424. class ze {
  3425. constructor(t) {
  3426. this.iter = t;
  3427. }
  3428. getNext() {
  3429. return this.iter.getNext().key;
  3430. }
  3431. hasNext() {
  3432. return this.iter.hasNext();
  3433. }
  3434. }
  3435. /**
  3436. * Compares two sorted sets for equality using their natural ordering. The
  3437. * method computes the intersection and invokes `onAdd` for every element that
  3438. * is in `after` but not `before`. `onRemove` is invoked for every element in
  3439. * `before` but missing from `after`.
  3440. *
  3441. * The method creates a copy of both `before` and `after` and runs in O(n log
  3442. * n), where n is the size of the two lists.
  3443. *
  3444. * @param before - The elements that exist in the original set.
  3445. * @param after - The elements to diff against the original set.
  3446. * @param comparator - The comparator for the elements in before and after.
  3447. * @param onAdd - A function to invoke for every element that is part of `
  3448. * after` but not `before`.
  3449. * @param onRemove - A function to invoke for every element that is part of
  3450. * `before` but not `after`.
  3451. */
  3452. /**
  3453. * Returns the next element from the iterator or `undefined` if none available.
  3454. */
  3455. function He(t) {
  3456. return t.hasNext() ? t.getNext() : void 0;
  3457. }
  3458. /**
  3459. * @license
  3460. * Copyright 2020 Google LLC
  3461. *
  3462. * Licensed under the Apache License, Version 2.0 (the "License");
  3463. * you may not use this file except in compliance with the License.
  3464. * You may obtain a copy of the License at
  3465. *
  3466. * http://www.apache.org/licenses/LICENSE-2.0
  3467. *
  3468. * Unless required by applicable law or agreed to in writing, software
  3469. * distributed under the License is distributed on an "AS IS" BASIS,
  3470. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3471. * See the License for the specific language governing permissions and
  3472. * limitations under the License.
  3473. */
  3474. /**
  3475. * Provides a set of fields that can be used to partially patch a document.
  3476. * FieldMask is used in conjunction with ObjectValue.
  3477. * Examples:
  3478. * foo - Overwrites foo entirely with the provided value. If foo is not
  3479. * present in the companion ObjectValue, the field is deleted.
  3480. * foo.bar - Overwrites only the field bar of the object foo.
  3481. * If foo is not an object, foo is replaced with an object
  3482. * containing foo
  3483. */ class Je {
  3484. constructor(t) {
  3485. this.fields = t,
  3486. // TODO(dimond): validation of FieldMask
  3487. // Sort the field mask to support `FieldMask.isEqual()` and assert below.
  3488. t.sort(ut.comparator);
  3489. }
  3490. static empty() {
  3491. return new Je([]);
  3492. }
  3493. /**
  3494. * Returns a new FieldMask object that is the result of adding all the given
  3495. * fields paths to this field mask.
  3496. */ unionWith(t) {
  3497. let e = new We(ut.comparator);
  3498. for (const t of this.fields) e = e.add(t);
  3499. for (const n of t) e = e.add(n);
  3500. return new Je(e.toArray());
  3501. }
  3502. /**
  3503. * Verifies that `fieldPath` is included by at least one field in this field
  3504. * mask.
  3505. *
  3506. * This is an O(n) operation, where `n` is the size of the field mask.
  3507. */ covers(t) {
  3508. for (const e of this.fields) if (e.isPrefixOf(t)) return !0;
  3509. return !1;
  3510. }
  3511. isEqual(t) {
  3512. return tt(this.fields, t.fields, ((t, e) => t.isEqual(e)));
  3513. }
  3514. }
  3515. /**
  3516. * @license
  3517. * Copyright 2017 Google LLC
  3518. *
  3519. * Licensed under the Apache License, Version 2.0 (the "License");
  3520. * you may not use this file except in compliance with the License.
  3521. * You may obtain a copy of the License at
  3522. *
  3523. * http://www.apache.org/licenses/LICENSE-2.0
  3524. *
  3525. * Unless required by applicable law or agreed to in writing, software
  3526. * distributed under the License is distributed on an "AS IS" BASIS,
  3527. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3528. * See the License for the specific language governing permissions and
  3529. * limitations under the License.
  3530. */
  3531. /**
  3532. * An ObjectValue represents a MapValue in the Firestore Proto and offers the
  3533. * ability to add and remove fields (via the ObjectValueBuilder).
  3534. */ class Ye {
  3535. constructor(t) {
  3536. this.value = t;
  3537. }
  3538. static empty() {
  3539. return new Ye({
  3540. mapValue: {}
  3541. });
  3542. }
  3543. /**
  3544. * Returns the value at the given path or null.
  3545. *
  3546. * @param path - the path to search
  3547. * @returns The value at the path or null if the path is not set.
  3548. */ field(t) {
  3549. if (t.isEmpty()) return this.value;
  3550. {
  3551. let e = this.value;
  3552. for (let n = 0; n < t.length - 1; ++n) if (e = (e.mapValue.fields || {})[t.get(n)],
  3553. !de(e)) return null;
  3554. return e = (e.mapValue.fields || {})[t.lastSegment()], e || null;
  3555. }
  3556. }
  3557. /**
  3558. * Sets the field to the provided value.
  3559. *
  3560. * @param path - The field path to set.
  3561. * @param value - The value to set.
  3562. */ set(t, e) {
  3563. this.getFieldsMap(t.popLast())[t.lastSegment()] = _e(e);
  3564. }
  3565. /**
  3566. * Sets the provided fields to the provided values.
  3567. *
  3568. * @param data - A map of fields to values (or null for deletes).
  3569. */ setAll(t) {
  3570. let e = ut.emptyPath(), n = {}, s = [];
  3571. t.forEach(((t, i) => {
  3572. if (!e.isImmediateParentOf(i)) {
  3573. // Insert the accumulated changes at this parent location
  3574. const t = this.getFieldsMap(e);
  3575. this.applyChanges(t, n, s), n = {}, s = [], e = i.popLast();
  3576. }
  3577. t ? n[i.lastSegment()] = _e(t) : s.push(i.lastSegment());
  3578. }));
  3579. const i = this.getFieldsMap(e);
  3580. this.applyChanges(i, n, s);
  3581. }
  3582. /**
  3583. * Removes the field at the specified path. If there is no field at the
  3584. * specified path, nothing is changed.
  3585. *
  3586. * @param path - The field path to remove.
  3587. */ delete(t) {
  3588. const e = this.field(t.popLast());
  3589. de(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()];
  3590. }
  3591. isEqual(t) {
  3592. return ne(this.value, t.value);
  3593. }
  3594. /**
  3595. * Returns the map that contains the leaf element of `path`. If the parent
  3596. * entry does not yet exist, or if it is not a map, a new map will be created.
  3597. */ getFieldsMap(t) {
  3598. let e = this.value;
  3599. e.mapValue.fields || (e.mapValue = {
  3600. fields: {}
  3601. });
  3602. for (let n = 0; n < t.length; ++n) {
  3603. let s = e.mapValue.fields[t.get(n)];
  3604. de(s) && s.mapValue.fields || (s = {
  3605. mapValue: {
  3606. fields: {}
  3607. }
  3608. }, e.mapValue.fields[t.get(n)] = s), e = s;
  3609. }
  3610. return e.mapValue.fields;
  3611. }
  3612. /**
  3613. * Modifies `fieldsMap` by adding, replacing or deleting the specified
  3614. * entries.
  3615. */ applyChanges(t, e, n) {
  3616. Bt(e, ((e, n) => t[e] = n));
  3617. for (const e of n) delete t[e];
  3618. }
  3619. clone() {
  3620. return new Ye(_e(this.value));
  3621. }
  3622. }
  3623. /**
  3624. * Returns a FieldMask built from all fields in a MapValue.
  3625. */ function Xe(t) {
  3626. const e = [];
  3627. return Bt(t.fields, ((t, n) => {
  3628. const s = new ut([ t ]);
  3629. if (de(n)) {
  3630. const t = Xe(n.mapValue).fields;
  3631. if (0 === t.length)
  3632. // Preserve the empty map by adding it to the FieldMask.
  3633. e.push(s); else
  3634. // For nested and non-empty ObjectValues, add the FieldPath of the
  3635. // leaf nodes.
  3636. for (const n of t) e.push(s.child(n));
  3637. } else
  3638. // For nested and non-empty ObjectValues, add the FieldPath of the leaf
  3639. // nodes.
  3640. e.push(s);
  3641. })), new Je(e);
  3642. }
  3643. /**
  3644. * @license
  3645. * Copyright 2017 Google LLC
  3646. *
  3647. * Licensed under the Apache License, Version 2.0 (the "License");
  3648. * you may not use this file except in compliance with the License.
  3649. * You may obtain a copy of the License at
  3650. *
  3651. * http://www.apache.org/licenses/LICENSE-2.0
  3652. *
  3653. * Unless required by applicable law or agreed to in writing, software
  3654. * distributed under the License is distributed on an "AS IS" BASIS,
  3655. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3656. * See the License for the specific language governing permissions and
  3657. * limitations under the License.
  3658. */
  3659. /**
  3660. * Represents a document in Firestore with a key, version, data and whether it
  3661. * has local mutations applied to it.
  3662. *
  3663. * Documents can transition between states via `convertToFoundDocument()`,
  3664. * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
  3665. * not transition to one of these states even after all mutations have been
  3666. * applied, `isValidDocument()` returns false and the document should be removed
  3667. * from all views.
  3668. */ class Ze {
  3669. constructor(t, e, n, s, i, r, o) {
  3670. this.key = t, this.documentType = e, this.version = n, this.readTime = s, this.createTime = i,
  3671. this.data = r, this.documentState = o;
  3672. }
  3673. /**
  3674. * Creates a document with no known version or data, but which can serve as
  3675. * base document for mutations.
  3676. */ static newInvalidDocument(t) {
  3677. return new Ze(t, 0 /* DocumentType.INVALID */ ,
  3678. /* version */ st.min(),
  3679. /* readTime */ st.min(),
  3680. /* createTime */ st.min(), Ye.empty(), 0 /* DocumentState.SYNCED */);
  3681. }
  3682. /**
  3683. * Creates a new document that is known to exist with the given data at the
  3684. * given version.
  3685. */ static newFoundDocument(t, e, n, s) {
  3686. return new Ze(t, 1 /* DocumentType.FOUND_DOCUMENT */ ,
  3687. /* version */ e,
  3688. /* readTime */ st.min(),
  3689. /* createTime */ n, s, 0 /* DocumentState.SYNCED */);
  3690. }
  3691. /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) {
  3692. return new Ze(t, 2 /* DocumentType.NO_DOCUMENT */ ,
  3693. /* version */ e,
  3694. /* readTime */ st.min(),
  3695. /* createTime */ st.min(), Ye.empty(), 0 /* DocumentState.SYNCED */);
  3696. }
  3697. /**
  3698. * Creates a new document that is known to exist at the given version but
  3699. * whose data is not known (e.g. a document that was updated without a known
  3700. * base document).
  3701. */ static newUnknownDocument(t, e) {
  3702. return new Ze(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  3703. /* version */ e,
  3704. /* readTime */ st.min(),
  3705. /* createTime */ st.min(), Ye.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);
  3706. }
  3707. /**
  3708. * Changes the document type to indicate that it exists and that its version
  3709. * and data are known.
  3710. */ convertToFoundDocument(t, e) {
  3711. // If a document is switching state from being an invalid or deleted
  3712. // document to a valid (FOUND_DOCUMENT) document, either due to receiving an
  3713. // update from Watch or due to applying a local set mutation on top
  3714. // of a deleted document, our best guess about its createTime would be the
  3715. // version at which the document transitioned to a FOUND_DOCUMENT.
  3716. return !this.createTime.isEqual(st.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t),
  3717. this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e,
  3718. this.documentState = 0 /* DocumentState.SYNCED */ , this;
  3719. }
  3720. /**
  3721. * Changes the document type to indicate that it doesn't exist at the given
  3722. * version.
  3723. */ convertToNoDocument(t) {
  3724. return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ ,
  3725. this.data = Ye.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , this;
  3726. }
  3727. /**
  3728. * Changes the document type to indicate that it exists at a given version but
  3729. * that its data is not known (e.g. a document that was updated without a known
  3730. * base document).
  3731. */ convertToUnknownDocument(t) {
  3732. return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ ,
  3733. this.data = Ye.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ ,
  3734. this;
  3735. }
  3736. setHasCommittedMutations() {
  3737. return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;
  3738. }
  3739. setHasLocalMutations() {
  3740. return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = st.min(),
  3741. this;
  3742. }
  3743. setReadTime(t) {
  3744. return this.readTime = t, this;
  3745. }
  3746. get hasLocalMutations() {
  3747. return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;
  3748. }
  3749. get hasCommittedMutations() {
  3750. return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;
  3751. }
  3752. get hasPendingWrites() {
  3753. return this.hasLocalMutations || this.hasCommittedMutations;
  3754. }
  3755. isValidDocument() {
  3756. return 0 /* DocumentType.INVALID */ !== this.documentType;
  3757. }
  3758. isFoundDocument() {
  3759. return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;
  3760. }
  3761. isNoDocument() {
  3762. return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;
  3763. }
  3764. isUnknownDocument() {
  3765. return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;
  3766. }
  3767. isEqual(t) {
  3768. return t instanceof Ze && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data);
  3769. }
  3770. mutableCopy() {
  3771. return new Ze(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);
  3772. }
  3773. toString() {
  3774. return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;
  3775. }
  3776. }
  3777. /**
  3778. * Compares the value for field `field` in the provided documents. Throws if
  3779. * the field does not exist in both documents.
  3780. */
  3781. /**
  3782. * @license
  3783. * Copyright 2019 Google LLC
  3784. *
  3785. * Licensed under the Apache License, Version 2.0 (the "License");
  3786. * you may not use this file except in compliance with the License.
  3787. * You may obtain a copy of the License at
  3788. *
  3789. * http://www.apache.org/licenses/LICENSE-2.0
  3790. *
  3791. * Unless required by applicable law or agreed to in writing, software
  3792. * distributed under the License is distributed on an "AS IS" BASIS,
  3793. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3794. * See the License for the specific language governing permissions and
  3795. * limitations under the License.
  3796. */
  3797. // Visible for testing
  3798. class tn {
  3799. constructor(t, e = null, n = [], s = [], i = null, r = null, o = null) {
  3800. this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = s, this.limit = i,
  3801. this.startAt = r, this.endAt = o, this.ft = null;
  3802. }
  3803. }
  3804. /**
  3805. * Initializes a Target with a path and optional additional query constraints.
  3806. * Path must currently be empty if this is a collection group query.
  3807. *
  3808. * NOTE: you should always construct `Target` from `Query.toTarget` instead of
  3809. * using this factory method, because `Query` provides an implicit `orderBy`
  3810. * property.
  3811. */ function en(t, e = null, n = [], s = [], i = null, r = null, o = null) {
  3812. return new tn(t, e, n, s, i, r, o);
  3813. }
  3814. function nn(t) {
  3815. const e = $(t);
  3816. if (null === e.ft) {
  3817. let t = e.path.canonicalString();
  3818. null !== e.collectionGroup && (t += "|cg:" + e.collectionGroup), t += "|f:", t += e.filters.map((t => De(t))).join(","),
  3819. t += "|ob:", t += e.orderBy.map((t => function(t) {
  3820. // TODO(b/29183165): Make this collision robust.
  3821. return t.field.canonicalString() + t.dir;
  3822. }(t))).join(","), qt(e.limit) || (t += "|l:", t += e.limit), e.startAt && (t += "|lb:",
  3823. t += e.startAt.inclusive ? "b:" : "a:", t += e.startAt.position.map((t => oe(t))).join(",")),
  3824. e.endAt && (t += "|ub:", t += e.endAt.inclusive ? "a:" : "b:", t += e.endAt.position.map((t => oe(t))).join(",")),
  3825. e.ft = t;
  3826. }
  3827. return e.ft;
  3828. }
  3829. function sn(t, e) {
  3830. if (t.limit !== e.limit) return !1;
  3831. if (t.orderBy.length !== e.orderBy.length) return !1;
  3832. for (let n = 0; n < t.orderBy.length; n++) if (!Ke(t.orderBy[n], e.orderBy[n])) return !1;
  3833. if (t.filters.length !== e.filters.length) return !1;
  3834. for (let n = 0; n < t.filters.length; n++) if (!Ce(t.filters[n], e.filters[n])) return !1;
  3835. return t.collectionGroup === e.collectionGroup && (!!t.path.isEqual(e.path) && (!!Ee(t.startAt, e.startAt) && Ee(t.endAt, e.endAt)));
  3836. }
  3837. function rn(t) {
  3838. return ct.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
  3839. }
  3840. /** Returns the field filters that target the given field path. */ function on(t, e) {
  3841. return t.filters.filter((t => t instanceof Re && t.field.isEqual(e)));
  3842. }
  3843. /**
  3844. * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
  3845. * filters. Returns `null` if there are no such filters.
  3846. */
  3847. /**
  3848. * Returns the value to use as the lower bound for ascending index segment at
  3849. * the provided `fieldPath` (or the upper bound for an descending segment).
  3850. */
  3851. function un(t, e, n) {
  3852. let s = te, i = !0;
  3853. // Process all filters to find a value for the current field segment
  3854. for (const n of on(t, e)) {
  3855. let t = te, e = !0;
  3856. switch (n.op) {
  3857. case "<" /* Operator.LESS_THAN */ :
  3858. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  3859. t = me(n.value);
  3860. break;
  3861. case "==" /* Operator.EQUAL */ :
  3862. case "in" /* Operator.IN */ :
  3863. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  3864. t = n.value;
  3865. break;
  3866. case ">" /* Operator.GREATER_THAN */ :
  3867. t = n.value, e = !1;
  3868. break;
  3869. case "!=" /* Operator.NOT_EQUAL */ :
  3870. case "not-in" /* Operator.NOT_IN */ :
  3871. t = te;
  3872. // Remaining filters cannot be used as lower bounds.
  3873. }
  3874. ye({
  3875. value: s,
  3876. inclusive: i
  3877. }, {
  3878. value: t,
  3879. inclusive: e
  3880. }) < 0 && (s = t, i = e);
  3881. }
  3882. // If there is an additional bound, compare the values against the existing
  3883. // range to see if we can narrow the scope.
  3884. if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {
  3885. if (t.orderBy[r].field.isEqual(e)) {
  3886. const t = n.position[r];
  3887. ye({
  3888. value: s,
  3889. inclusive: i
  3890. }, {
  3891. value: t,
  3892. inclusive: n.inclusive
  3893. }) < 0 && (s = t, i = n.inclusive);
  3894. break;
  3895. }
  3896. }
  3897. return {
  3898. value: s,
  3899. inclusive: i
  3900. };
  3901. }
  3902. /**
  3903. * Returns the value to use as the upper bound for ascending index segment at
  3904. * the provided `fieldPath` (or the lower bound for a descending segment).
  3905. */ function cn(t, e, n) {
  3906. let s = Zt, i = !0;
  3907. // Process all filters to find a value for the current field segment
  3908. for (const n of on(t, e)) {
  3909. let t = Zt, e = !0;
  3910. switch (n.op) {
  3911. case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
  3912. case ">" /* Operator.GREATER_THAN */ :
  3913. t = ge(n.value), e = !1;
  3914. break;
  3915. case "==" /* Operator.EQUAL */ :
  3916. case "in" /* Operator.IN */ :
  3917. case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
  3918. t = n.value;
  3919. break;
  3920. case "<" /* Operator.LESS_THAN */ :
  3921. t = n.value, e = !1;
  3922. break;
  3923. case "!=" /* Operator.NOT_EQUAL */ :
  3924. case "not-in" /* Operator.NOT_IN */ :
  3925. t = Zt;
  3926. // Remaining filters cannot be used as upper bounds.
  3927. }
  3928. pe({
  3929. value: s,
  3930. inclusive: i
  3931. }, {
  3932. value: t,
  3933. inclusive: e
  3934. }) > 0 && (s = t, i = e);
  3935. }
  3936. // If there is an additional bound, compare the values against the existing
  3937. // range to see if we can narrow the scope.
  3938. if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {
  3939. if (t.orderBy[r].field.isEqual(e)) {
  3940. const t = n.position[r];
  3941. pe({
  3942. value: s,
  3943. inclusive: i
  3944. }, {
  3945. value: t,
  3946. inclusive: n.inclusive
  3947. }) > 0 && (s = t, i = n.inclusive);
  3948. break;
  3949. }
  3950. }
  3951. return {
  3952. value: s,
  3953. inclusive: i
  3954. };
  3955. }
  3956. /** Returns the number of segments of a perfect index for this target. */
  3957. /**
  3958. * @license
  3959. * Copyright 2017 Google LLC
  3960. *
  3961. * Licensed under the Apache License, Version 2.0 (the "License");
  3962. * you may not use this file except in compliance with the License.
  3963. * You may obtain a copy of the License at
  3964. *
  3965. * http://www.apache.org/licenses/LICENSE-2.0
  3966. *
  3967. * Unless required by applicable law or agreed to in writing, software
  3968. * distributed under the License is distributed on an "AS IS" BASIS,
  3969. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3970. * See the License for the specific language governing permissions and
  3971. * limitations under the License.
  3972. */
  3973. /**
  3974. * Query encapsulates all the query attributes we support in the SDK. It can
  3975. * be run against the LocalStore, as well as be converted to a `Target` to
  3976. * query the RemoteStore results.
  3977. *
  3978. * Visible for testing.
  3979. */
  3980. class an {
  3981. /**
  3982. * Initializes a Query with a path and optional additional query constraints.
  3983. * Path must currently be empty if this is a collection group query.
  3984. */
  3985. constructor(t, e = null, n = [], s = [], i = null, r = "F" /* LimitType.First */ , o = null, u = null) {
  3986. this.path = t, this.collectionGroup = e, this.explicitOrderBy = n, this.filters = s,
  3987. this.limit = i, this.limitType = r, this.startAt = o, this.endAt = u, this.dt = null,
  3988. // The corresponding `Target` of this `Query` instance.
  3989. this._t = null, this.startAt, this.endAt;
  3990. }
  3991. }
  3992. /** Creates a new Query instance with the options provided. */ function hn(t, e, n, s, i, r, o, u) {
  3993. return new an(t, e, n, s, i, r, o, u);
  3994. }
  3995. /** Creates a new Query for a query that matches all documents at `path` */ function ln(t) {
  3996. return new an(t);
  3997. }
  3998. /**
  3999. * Helper to convert a collection group query into a collection query at a
  4000. * specific path. This is used when executing collection group queries, since
  4001. * we have to split the query into a set of collection queries at multiple
  4002. * paths.
  4003. */
  4004. /**
  4005. * Returns true if this query does not specify any query constraints that
  4006. * could remove results.
  4007. */
  4008. function fn(t) {
  4009. 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());
  4010. }
  4011. function dn(t) {
  4012. return t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null;
  4013. }
  4014. function _n(t) {
  4015. for (const e of t.filters) {
  4016. const t = e.getFirstInequalityField();
  4017. if (null !== t) return t;
  4018. }
  4019. return null;
  4020. }
  4021. /**
  4022. * Creates a new Query for a collection group query that matches all documents
  4023. * within the provided collection group.
  4024. */
  4025. /**
  4026. * Returns whether the query matches a collection group rather than a specific
  4027. * collection.
  4028. */
  4029. function wn(t) {
  4030. return null !== t.collectionGroup;
  4031. }
  4032. /**
  4033. * Returns the implicit order by constraint that is used to execute the Query,
  4034. * which can be different from the order by constraints the user provided (e.g.
  4035. * the SDK and backend always orders by `__name__`).
  4036. */ function mn(t) {
  4037. const e = $(t);
  4038. if (null === e.dt) {
  4039. e.dt = [];
  4040. const t = _n(e), n = dn(e);
  4041. if (null !== t && null === n)
  4042. // In order to implicitly add key ordering, we must also add the
  4043. // inequality filter field for it to be a valid query.
  4044. // Note that the default inequality field and key ordering is ascending.
  4045. t.isKeyField() || e.dt.push(new Ue(t)), e.dt.push(new Ue(ut.keyField(), "asc" /* Direction.ASCENDING */)); else {
  4046. let t = !1;
  4047. for (const n of e.explicitOrderBy) e.dt.push(n), n.field.isKeyField() && (t = !0);
  4048. if (!t) {
  4049. // The order of the implicit key ordering always matches the last
  4050. // explicit order by
  4051. const t = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */;
  4052. e.dt.push(new Ue(ut.keyField(), t));
  4053. }
  4054. }
  4055. }
  4056. return e.dt;
  4057. }
  4058. /**
  4059. * Converts this `Query` instance to it's corresponding `Target` representation.
  4060. */ function gn(t) {
  4061. const e = $(t);
  4062. if (!e._t) if ("F" /* LimitType.First */ === e.limitType) e._t = en(e.path, e.collectionGroup, mn(e), e.filters, e.limit, e.startAt, e.endAt); else {
  4063. // Flip the orderBy directions since we want the last results
  4064. const t = [];
  4065. for (const n of mn(e)) {
  4066. const e = "desc" /* Direction.DESCENDING */ === n.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */;
  4067. t.push(new Ue(n.field, e));
  4068. }
  4069. // We need to swap the cursors to match the now-flipped query ordering.
  4070. const n = e.endAt ? new Ie(e.endAt.position, e.endAt.inclusive) : null, s = e.startAt ? new Ie(e.startAt.position, e.startAt.inclusive) : null;
  4071. // Now return as a LimitType.First query.
  4072. e._t = en(e.path, e.collectionGroup, t, e.filters, e.limit, n, s);
  4073. }
  4074. return e._t;
  4075. }
  4076. function yn(t, e) {
  4077. e.getFirstInequalityField(), _n(t);
  4078. const n = t.filters.concat([ e ]);
  4079. return new an(t.path, t.collectionGroup, t.explicitOrderBy.slice(), n, t.limit, t.limitType, t.startAt, t.endAt);
  4080. }
  4081. function pn(t, e, n) {
  4082. return new an(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, n, t.startAt, t.endAt);
  4083. }
  4084. function In(t, e) {
  4085. return sn(gn(t), gn(e)) && t.limitType === e.limitType;
  4086. }
  4087. // TODO(b/29183165): This is used to get a unique string from a query to, for
  4088. // example, use as a dictionary key, but the implementation is subject to
  4089. // collisions. Make it collision-free.
  4090. function Tn(t) {
  4091. return `${nn(gn(t))}|lt:${t.limitType}`;
  4092. }
  4093. function En(t) {
  4094. return `Query(target=${function(t) {
  4095. let e = t.path.canonicalString();
  4096. return null !== t.collectionGroup && (e += " collectionGroup=" + t.collectionGroup),
  4097. t.filters.length > 0 && (e += `, filters: [${t.filters.map((t => Ne(t))).join(", ")}]`),
  4098. qt(t.limit) || (e += ", limit: " + t.limit), t.orderBy.length > 0 && (e += `, orderBy: [${t.orderBy.map((t => function(t) {
  4099. return `${t.field.canonicalString()} (${t.dir})`;
  4100. }(t))).join(", ")}]`), t.startAt && (e += ", startAt: ", e += t.startAt.inclusive ? "b:" : "a:",
  4101. e += t.startAt.position.map((t => oe(t))).join(",")), t.endAt && (e += ", endAt: ",
  4102. e += t.endAt.inclusive ? "a:" : "b:", e += t.endAt.position.map((t => oe(t))).join(",")),
  4103. `Target(${e})`;
  4104. }(gn(t))}; limitType=${t.limitType})`;
  4105. }
  4106. /** Returns whether `doc` matches the constraints of `query`. */ function An(t, e) {
  4107. return e.isFoundDocument() && function(t, e) {
  4108. const n = e.key.path;
  4109. return null !== t.collectionGroup ? e.key.hasCollectionId(t.collectionGroup) && t.path.isPrefixOf(n) : ct.isDocumentKey(t.path) ? t.path.isEqual(n) : t.path.isImmediateParentOf(n);
  4110. }
  4111. /**
  4112. * A document must have a value for every ordering clause in order to show up
  4113. * in the results.
  4114. */ (t, e) && function(t, e) {
  4115. // We must use `queryOrderBy()` to get the list of all orderBys (both implicit and explicit).
  4116. // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must
  4117. // be taken into account. For example, the query "a > 1 || b==1" has an implicit "orderBy a" due
  4118. // to the inequality, and is evaluated as "a > 1 orderBy a || b==1 orderBy a".
  4119. // A document with content of {b:1} matches the filters, but does not match the orderBy because
  4120. // it's missing the field 'a'.
  4121. for (const n of mn(t))
  4122. // order by key always matches
  4123. if (!n.field.isKeyField() && null === e.data.field(n.field)) return !1;
  4124. return !0;
  4125. }(t, e) && function(t, e) {
  4126. for (const n of t.filters) if (!n.matches(e)) return !1;
  4127. return !0;
  4128. }
  4129. /** Makes sure a document is within the bounds, if provided. */ (t, e) && function(t, e) {
  4130. if (t.startAt && !
  4131. /**
  4132. * Returns true if a document sorts before a bound using the provided sort
  4133. * order.
  4134. */
  4135. function(t, e, n) {
  4136. const s = Te(t, e, n);
  4137. return t.inclusive ? s <= 0 : s < 0;
  4138. }(t.startAt, mn(t), e)) return !1;
  4139. if (t.endAt && !function(t, e, n) {
  4140. const s = Te(t, e, n);
  4141. return t.inclusive ? s >= 0 : s > 0;
  4142. }(t.endAt, mn(t), e)) return !1;
  4143. return !0;
  4144. }
  4145. /**
  4146. * Returns the collection group that this query targets.
  4147. *
  4148. * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab
  4149. * synchronization for query results.
  4150. */ (t, e);
  4151. }
  4152. function Rn(t) {
  4153. return t.collectionGroup || (t.path.length % 2 == 1 ? t.path.lastSegment() : t.path.get(t.path.length - 2));
  4154. }
  4155. /**
  4156. * Returns a new comparator function that can be used to compare two documents
  4157. * based on the Query's ordering constraint.
  4158. */ function bn(t) {
  4159. return (e, n) => {
  4160. let s = !1;
  4161. for (const i of mn(t)) {
  4162. const t = Pn(i, e, n);
  4163. if (0 !== t) return t;
  4164. s = s || i.field.isKeyField();
  4165. }
  4166. return 0;
  4167. };
  4168. }
  4169. function Pn(t, e, n) {
  4170. const s = t.field.isKeyField() ? ct.comparator(e.key, n.key) : function(t, e, n) {
  4171. const s = e.data.field(t), i = n.data.field(t);
  4172. return null !== s && null !== i ? ie(s, i) : O();
  4173. }(t.field, e, n);
  4174. switch (t.dir) {
  4175. case "asc" /* Direction.ASCENDING */ :
  4176. return s;
  4177. case "desc" /* Direction.DESCENDING */ :
  4178. return -1 * s;
  4179. default:
  4180. return O();
  4181. }
  4182. }
  4183. /**
  4184. * @license
  4185. * Copyright 2020 Google LLC
  4186. *
  4187. * Licensed under the Apache License, Version 2.0 (the "License");
  4188. * you may not use this file except in compliance with the License.
  4189. * You may obtain a copy of the License at
  4190. *
  4191. * http://www.apache.org/licenses/LICENSE-2.0
  4192. *
  4193. * Unless required by applicable law or agreed to in writing, software
  4194. * distributed under the License is distributed on an "AS IS" BASIS,
  4195. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4196. * See the License for the specific language governing permissions and
  4197. * limitations under the License.
  4198. */
  4199. /**
  4200. * Returns an DoubleValue for `value` that is encoded based the serializer's
  4201. * `useProto3Json` setting.
  4202. */ function vn(t, e) {
  4203. if (t.wt) {
  4204. if (isNaN(e)) return {
  4205. doubleValue: "NaN"
  4206. };
  4207. if (e === 1 / 0) return {
  4208. doubleValue: "Infinity"
  4209. };
  4210. if (e === -1 / 0) return {
  4211. doubleValue: "-Infinity"
  4212. };
  4213. }
  4214. return {
  4215. doubleValue: Ut(e) ? "-0" : e
  4216. };
  4217. }
  4218. /**
  4219. * Returns an IntegerValue for `value`.
  4220. */ function Vn(t) {
  4221. return {
  4222. integerValue: "" + t
  4223. };
  4224. }
  4225. /**
  4226. * Returns a value for a number that's appropriate to put into a proto.
  4227. * The return value is an IntegerValue if it can safely represent the value,
  4228. * otherwise a DoubleValue is returned.
  4229. */ function Sn(t, e) {
  4230. return Kt(e) ? Vn(e) : vn(t, e);
  4231. }
  4232. /**
  4233. * @license
  4234. * Copyright 2018 Google LLC
  4235. *
  4236. * Licensed under the Apache License, Version 2.0 (the "License");
  4237. * you may not use this file except in compliance with the License.
  4238. * You may obtain a copy of the License at
  4239. *
  4240. * http://www.apache.org/licenses/LICENSE-2.0
  4241. *
  4242. * Unless required by applicable law or agreed to in writing, software
  4243. * distributed under the License is distributed on an "AS IS" BASIS,
  4244. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4245. * See the License for the specific language governing permissions and
  4246. * limitations under the License.
  4247. */
  4248. /** Used to represent a field transform on a mutation. */ class Dn {
  4249. constructor() {
  4250. // Make sure that the structural type of `TransformOperation` is unique.
  4251. // See https://github.com/microsoft/TypeScript/issues/5451
  4252. this._ = void 0;
  4253. }
  4254. }
  4255. /**
  4256. * Computes the local transform result against the provided `previousValue`,
  4257. * optionally using the provided localWriteTime.
  4258. */ function Cn(t, e, n) {
  4259. return t instanceof kn ? function(t, e) {
  4260. const n = {
  4261. fields: {
  4262. __type__: {
  4263. stringValue: "server_timestamp"
  4264. },
  4265. __local_write_time__: {
  4266. timestampValue: {
  4267. seconds: t.seconds,
  4268. nanos: t.nanoseconds
  4269. }
  4270. }
  4271. }
  4272. };
  4273. return e && (n.fields.__previous_value__ = e), {
  4274. mapValue: n
  4275. };
  4276. }(n, e) : t instanceof On ? Mn(t, e) : t instanceof Fn ? $n(t, e) : function(t, e) {
  4277. // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit
  4278. // precision and resolves overflows by reducing precision, we do not
  4279. // manually cap overflows at 2^63.
  4280. const n = Nn(t, e), s = Ln(n) + Ln(t.gt);
  4281. return ae(n) && ae(t.gt) ? Vn(s) : vn(t.yt, s);
  4282. }(t, e);
  4283. }
  4284. /**
  4285. * Computes a final transform result after the transform has been acknowledged
  4286. * by the server, potentially using the server-provided transformResult.
  4287. */ function xn(t, e, n) {
  4288. // The server just sends null as the transform result for array operations,
  4289. // so we have to calculate a result the same as we do for local
  4290. // applications.
  4291. return t instanceof On ? Mn(t, e) : t instanceof Fn ? $n(t, e) : n;
  4292. }
  4293. /**
  4294. * If this transform operation is not idempotent, returns the base value to
  4295. * persist for this transform. If a base value is returned, the transform
  4296. * operation is always applied to this base value, even if document has
  4297. * already been updated.
  4298. *
  4299. * Base values provide consistent behavior for non-idempotent transforms and
  4300. * allow us to return the same latency-compensated value even if the backend
  4301. * has already applied the transform operation. The base value is null for
  4302. * idempotent transforms, as they can be re-played even if the backend has
  4303. * already applied them.
  4304. *
  4305. * @returns a base value to store along with the mutation, or null for
  4306. * idempotent transforms.
  4307. */ function Nn(t, e) {
  4308. return t instanceof Bn ? ae(n = e) || function(t) {
  4309. return !!t && "doubleValue" in t;
  4310. }
  4311. /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ (n) ? e : {
  4312. integerValue: 0
  4313. } : null;
  4314. var n;
  4315. }
  4316. /** Transforms a value into a server-generated timestamp. */
  4317. class kn extends Dn {}
  4318. /** Transforms an array value via a union operation. */ class On extends Dn {
  4319. constructor(t) {
  4320. super(), this.elements = t;
  4321. }
  4322. }
  4323. function Mn(t, e) {
  4324. const n = qn(e);
  4325. for (const e of t.elements) n.some((t => ne(t, e))) || n.push(e);
  4326. return {
  4327. arrayValue: {
  4328. values: n
  4329. }
  4330. };
  4331. }
  4332. /** Transforms an array value via a remove operation. */ class Fn extends Dn {
  4333. constructor(t) {
  4334. super(), this.elements = t;
  4335. }
  4336. }
  4337. function $n(t, e) {
  4338. let n = qn(e);
  4339. for (const e of t.elements) n = n.filter((t => !ne(t, e)));
  4340. return {
  4341. arrayValue: {
  4342. values: n
  4343. }
  4344. };
  4345. }
  4346. /**
  4347. * Implements the backend semantics for locally computed NUMERIC_ADD (increment)
  4348. * transforms. Converts all field values to integers or doubles, but unlike the
  4349. * backend does not cap integer values at 2^63. Instead, JavaScript number
  4350. * arithmetic is used and precision loss can occur for values greater than 2^53.
  4351. */ class Bn extends Dn {
  4352. constructor(t, e) {
  4353. super(), this.yt = t, this.gt = e;
  4354. }
  4355. }
  4356. function Ln(t) {
  4357. return zt(t.integerValue || t.doubleValue);
  4358. }
  4359. function qn(t) {
  4360. return he(t) && t.arrayValue.values ? t.arrayValue.values.slice() : [];
  4361. }
  4362. /**
  4363. * @license
  4364. * Copyright 2017 Google LLC
  4365. *
  4366. * Licensed under the Apache License, Version 2.0 (the "License");
  4367. * you may not use this file except in compliance with the License.
  4368. * You may obtain a copy of the License at
  4369. *
  4370. * http://www.apache.org/licenses/LICENSE-2.0
  4371. *
  4372. * Unless required by applicable law or agreed to in writing, software
  4373. * distributed under the License is distributed on an "AS IS" BASIS,
  4374. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4375. * See the License for the specific language governing permissions and
  4376. * limitations under the License.
  4377. */
  4378. /** A field path and the TransformOperation to perform upon it. */ class Un {
  4379. constructor(t, e) {
  4380. this.field = t, this.transform = e;
  4381. }
  4382. }
  4383. function Kn(t, e) {
  4384. return t.field.isEqual(e.field) && function(t, e) {
  4385. return t instanceof On && e instanceof On || t instanceof Fn && e instanceof Fn ? tt(t.elements, e.elements, ne) : t instanceof Bn && e instanceof Bn ? ne(t.gt, e.gt) : t instanceof kn && e instanceof kn;
  4386. }(t.transform, e.transform);
  4387. }
  4388. /** The result of successfully applying a mutation to the backend. */
  4389. class Gn {
  4390. constructor(
  4391. /**
  4392. * The version at which the mutation was committed:
  4393. *
  4394. * - For most operations, this is the updateTime in the WriteResult.
  4395. * - For deletes, the commitTime of the WriteResponse (because deletes are
  4396. * not stored and have no updateTime).
  4397. *
  4398. * Note that these versions can be different: No-op writes will not change
  4399. * the updateTime even though the commitTime advances.
  4400. */
  4401. t,
  4402. /**
  4403. * The resulting fields returned from the backend after a mutation
  4404. * containing field transforms has been committed. Contains one FieldValue
  4405. * for each FieldTransform that was in the mutation.
  4406. *
  4407. * Will be empty if the mutation did not contain any field transforms.
  4408. */
  4409. e) {
  4410. this.version = t, this.transformResults = e;
  4411. }
  4412. }
  4413. /**
  4414. * Encodes a precondition for a mutation. This follows the model that the
  4415. * backend accepts with the special case of an explicit "empty" precondition
  4416. * (meaning no precondition).
  4417. */ class Qn {
  4418. constructor(t, e) {
  4419. this.updateTime = t, this.exists = e;
  4420. }
  4421. /** Creates a new empty Precondition. */ static none() {
  4422. return new Qn;
  4423. }
  4424. /** Creates a new Precondition with an exists flag. */ static exists(t) {
  4425. return new Qn(void 0, t);
  4426. }
  4427. /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) {
  4428. return new Qn(t);
  4429. }
  4430. /** Returns whether this Precondition is empty. */ get isNone() {
  4431. return void 0 === this.updateTime && void 0 === this.exists;
  4432. }
  4433. isEqual(t) {
  4434. return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);
  4435. }
  4436. }
  4437. /** Returns true if the preconditions is valid for the given document. */ function jn(t, e) {
  4438. return void 0 !== t.updateTime ? e.isFoundDocument() && e.version.isEqual(t.updateTime) : void 0 === t.exists || t.exists === e.isFoundDocument();
  4439. }
  4440. /**
  4441. * A mutation describes a self-contained change to a document. Mutations can
  4442. * create, replace, delete, and update subsets of documents.
  4443. *
  4444. * Mutations not only act on the value of the document but also its version.
  4445. *
  4446. * For local mutations (mutations that haven't been committed yet), we preserve
  4447. * the existing version for Set and Patch mutations. For Delete mutations, we
  4448. * reset the version to 0.
  4449. *
  4450. * Here's the expected transition table.
  4451. *
  4452. * MUTATION APPLIED TO RESULTS IN
  4453. *
  4454. * SetMutation Document(v3) Document(v3)
  4455. * SetMutation NoDocument(v3) Document(v0)
  4456. * SetMutation InvalidDocument(v0) Document(v0)
  4457. * PatchMutation Document(v3) Document(v3)
  4458. * PatchMutation NoDocument(v3) NoDocument(v3)
  4459. * PatchMutation InvalidDocument(v0) UnknownDocument(v3)
  4460. * DeleteMutation Document(v3) NoDocument(v0)
  4461. * DeleteMutation NoDocument(v3) NoDocument(v0)
  4462. * DeleteMutation InvalidDocument(v0) NoDocument(v0)
  4463. *
  4464. * For acknowledged mutations, we use the updateTime of the WriteResponse as
  4465. * the resulting version for Set and Patch mutations. As deletes have no
  4466. * explicit update time, we use the commitTime of the WriteResponse for
  4467. * Delete mutations.
  4468. *
  4469. * If a mutation is acknowledged by the backend but fails the precondition check
  4470. * locally, we transition to an `UnknownDocument` and rely on Watch to send us
  4471. * the updated version.
  4472. *
  4473. * Field transforms are used only with Patch and Set Mutations. We use the
  4474. * `updateTransforms` message to store transforms, rather than the `transforms`s
  4475. * messages.
  4476. *
  4477. * ## Subclassing Notes
  4478. *
  4479. * Every type of mutation needs to implement its own applyToRemoteDocument() and
  4480. * applyToLocalView() to implement the actual behavior of applying the mutation
  4481. * to some source document (see `setMutationApplyToRemoteDocument()` for an
  4482. * example).
  4483. */ class Wn {}
  4484. /**
  4485. * A utility method to calculate a `Mutation` representing the overlay from the
  4486. * final state of the document, and a `FieldMask` representing the fields that
  4487. * are mutated by the local mutations.
  4488. */ function zn(t, e) {
  4489. if (!t.hasLocalMutations || e && 0 === e.fields.length) return null;
  4490. // mask is null when sets or deletes are applied to the current document.
  4491. if (null === e) return t.isNoDocument() ? new is(t.key, Qn.none()) : new Zn(t.key, t.data, Qn.none());
  4492. {
  4493. const n = t.data, s = Ye.empty();
  4494. let i = new We(ut.comparator);
  4495. for (let t of e.fields) if (!i.has(t)) {
  4496. let e = n.field(t);
  4497. // If we are deleting a nested field, we take the immediate parent as
  4498. // the mask used to construct the resulting mutation.
  4499. // Justification: Nested fields can create parent fields implicitly. If
  4500. // only a leaf entry is deleted in later mutations, the parent field
  4501. // should still remain, but we may have lost this information.
  4502. // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).
  4503. // This leaves the final result (foo, {}). Despite the fact that `doc`
  4504. // has the correct result, `foo` is not in `mask`, and the resulting
  4505. // mutation would miss `foo`.
  4506. null === e && t.length > 1 && (t = t.popLast(), e = n.field(t)), null === e ? s.delete(t) : s.set(t, e),
  4507. i = i.add(t);
  4508. }
  4509. return new ts(t.key, s, new Je(i.toArray()), Qn.none());
  4510. }
  4511. }
  4512. /**
  4513. * Applies this mutation to the given document for the purposes of computing a
  4514. * new remote document. If the input document doesn't match the expected state
  4515. * (e.g. it is invalid or outdated), the document type may transition to
  4516. * unknown.
  4517. *
  4518. * @param mutation - The mutation to apply.
  4519. * @param document - The document to mutate. The input document can be an
  4520. * invalid document if the client has no knowledge of the pre-mutation state
  4521. * of the document.
  4522. * @param mutationResult - The result of applying the mutation from the backend.
  4523. */ function Hn(t, e, n) {
  4524. t instanceof Zn ? function(t, e, n) {
  4525. // Unlike setMutationApplyToLocalView, if we're applying a mutation to a
  4526. // remote document the server has accepted the mutation so the precondition
  4527. // must have held.
  4528. const s = t.value.clone(), i = ns(t.fieldTransforms, e, n.transformResults);
  4529. s.setAll(i), e.convertToFoundDocument(n.version, s).setHasCommittedMutations();
  4530. }(t, e, n) : t instanceof ts ? function(t, e, n) {
  4531. if (!jn(t.precondition, e))
  4532. // Since the mutation was not rejected, we know that the precondition
  4533. // matched on the backend. We therefore must not have the expected version
  4534. // of the document in our cache and convert to an UnknownDocument with a
  4535. // known updateTime.
  4536. return void e.convertToUnknownDocument(n.version);
  4537. const s = ns(t.fieldTransforms, e, n.transformResults), i = e.data;
  4538. i.setAll(es(t)), i.setAll(s), e.convertToFoundDocument(n.version, i).setHasCommittedMutations();
  4539. }(t, e, n) : function(t, e, n) {
  4540. // Unlike applyToLocalView, if we're applying a mutation to a remote
  4541. // document the server has accepted the mutation so the precondition must
  4542. // have held.
  4543. e.convertToNoDocument(n.version).setHasCommittedMutations();
  4544. }(0, e, n);
  4545. }
  4546. /**
  4547. * Applies this mutation to the given document for the purposes of computing
  4548. * the new local view of a document. If the input document doesn't match the
  4549. * expected state, the document is not modified.
  4550. *
  4551. * @param mutation - The mutation to apply.
  4552. * @param document - The document to mutate. The input document can be an
  4553. * invalid document if the client has no knowledge of the pre-mutation state
  4554. * of the document.
  4555. * @param previousMask - The fields that have been updated before applying this mutation.
  4556. * @param localWriteTime - A timestamp indicating the local write time of the
  4557. * batch this mutation is a part of.
  4558. * @returns A `FieldMask` representing the fields that are changed by applying this mutation.
  4559. */ function Jn(t, e, n, s) {
  4560. return t instanceof Zn ? function(t, e, n, s) {
  4561. if (!jn(t.precondition, e))
  4562. // The mutation failed to apply (e.g. a document ID created with add()
  4563. // caused a name collision).
  4564. return n;
  4565. const i = t.value.clone(), r = ss(t.fieldTransforms, s, e);
  4566. return i.setAll(r), e.convertToFoundDocument(e.version, i).setHasLocalMutations(),
  4567. null;
  4568. // SetMutation overwrites all fields.
  4569. }
  4570. /**
  4571. * A mutation that modifies fields of the document at the given key with the
  4572. * given values. The values are applied through a field mask:
  4573. *
  4574. * * When a field is in both the mask and the values, the corresponding field
  4575. * is updated.
  4576. * * When a field is in neither the mask nor the values, the corresponding
  4577. * field is unmodified.
  4578. * * When a field is in the mask but not in the values, the corresponding field
  4579. * is deleted.
  4580. * * When a field is not in the mask but is in the values, the values map is
  4581. * ignored.
  4582. */ (t, e, n, s) : t instanceof ts ? function(t, e, n, s) {
  4583. if (!jn(t.precondition, e)) return n;
  4584. const i = ss(t.fieldTransforms, s, e), r = e.data;
  4585. if (r.setAll(es(t)), r.setAll(i), e.convertToFoundDocument(e.version, r).setHasLocalMutations(),
  4586. null === n) return null;
  4587. return n.unionWith(t.fieldMask.fields).unionWith(t.fieldTransforms.map((t => t.field)));
  4588. }
  4589. /**
  4590. * Returns a FieldPath/Value map with the content of the PatchMutation.
  4591. */ (t, e, n, s) : function(t, e, n) {
  4592. if (jn(t.precondition, e)) return e.convertToNoDocument(e.version).setHasLocalMutations(),
  4593. null;
  4594. return n;
  4595. }
  4596. /**
  4597. * A mutation that verifies the existence of the document at the given key with
  4598. * the provided precondition.
  4599. *
  4600. * The `verify` operation is only used in Transactions, and this class serves
  4601. * primarily to facilitate serialization into protos.
  4602. */ (t, e, n);
  4603. }
  4604. /**
  4605. * If this mutation is not idempotent, returns the base value to persist with
  4606. * this mutation. If a base value is returned, the mutation is always applied
  4607. * to this base value, even if document has already been updated.
  4608. *
  4609. * The base value is a sparse object that consists of only the document
  4610. * fields for which this mutation contains a non-idempotent transformation
  4611. * (e.g. a numeric increment). The provided value guarantees consistent
  4612. * behavior for non-idempotent transforms and allow us to return the same
  4613. * latency-compensated value even if the backend has already applied the
  4614. * mutation. The base value is null for idempotent mutations, as they can be
  4615. * re-played even if the backend has already applied them.
  4616. *
  4617. * @returns a base value to store along with the mutation, or null for
  4618. * idempotent mutations.
  4619. */ function Yn(t, e) {
  4620. let n = null;
  4621. for (const s of t.fieldTransforms) {
  4622. const t = e.data.field(s.field), i = Nn(s.transform, t || null);
  4623. null != i && (null === n && (n = Ye.empty()), n.set(s.field, i));
  4624. }
  4625. return n || null;
  4626. }
  4627. function Xn(t, e) {
  4628. return t.type === e.type && (!!t.key.isEqual(e.key) && (!!t.precondition.isEqual(e.precondition) && (!!function(t, e) {
  4629. return void 0 === t && void 0 === e || !(!t || !e) && tt(t, e, ((t, e) => Kn(t, e)));
  4630. }(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)))));
  4631. }
  4632. /**
  4633. * A mutation that creates or replaces the document at the given key with the
  4634. * object value contents.
  4635. */ class Zn extends Wn {
  4636. constructor(t, e, n, s = []) {
  4637. super(), this.key = t, this.value = e, this.precondition = n, this.fieldTransforms = s,
  4638. this.type = 0 /* MutationType.Set */;
  4639. }
  4640. getFieldMask() {
  4641. return null;
  4642. }
  4643. }
  4644. class ts extends Wn {
  4645. constructor(t, e, n, s, i = []) {
  4646. super(), this.key = t, this.data = e, this.fieldMask = n, this.precondition = s,
  4647. this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */;
  4648. }
  4649. getFieldMask() {
  4650. return this.fieldMask;
  4651. }
  4652. }
  4653. function es(t) {
  4654. const e = new Map;
  4655. return t.fieldMask.fields.forEach((n => {
  4656. if (!n.isEmpty()) {
  4657. const s = t.data.field(n);
  4658. e.set(n, s);
  4659. }
  4660. })), e;
  4661. }
  4662. /**
  4663. * Creates a list of "transform results" (a transform result is a field value
  4664. * representing the result of applying a transform) for use after a mutation
  4665. * containing transforms has been acknowledged by the server.
  4666. *
  4667. * @param fieldTransforms - The field transforms to apply the result to.
  4668. * @param mutableDocument - The current state of the document after applying all
  4669. * previous mutations.
  4670. * @param serverTransformResults - The transform results received by the server.
  4671. * @returns The transform results list.
  4672. */ function ns(t, e, n) {
  4673. const s = new Map;
  4674. M(t.length === n.length);
  4675. for (let i = 0; i < n.length; i++) {
  4676. const r = t[i], o = r.transform, u = e.data.field(r.field);
  4677. s.set(r.field, xn(o, u, n[i]));
  4678. }
  4679. return s;
  4680. }
  4681. /**
  4682. * Creates a list of "transform results" (a transform result is a field value
  4683. * representing the result of applying a transform) for use when applying a
  4684. * transform locally.
  4685. *
  4686. * @param fieldTransforms - The field transforms to apply the result to.
  4687. * @param localWriteTime - The local time of the mutation (used to
  4688. * generate ServerTimestampValues).
  4689. * @param mutableDocument - The document to apply transforms on.
  4690. * @returns The transform results list.
  4691. */ function ss(t, e, n) {
  4692. const s = new Map;
  4693. for (const i of t) {
  4694. const t = i.transform, r = n.data.field(i.field);
  4695. s.set(i.field, Cn(t, r, e));
  4696. }
  4697. return s;
  4698. }
  4699. /** A mutation that deletes the document at the given key. */ class is extends Wn {
  4700. constructor(t, e) {
  4701. super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ ,
  4702. this.fieldTransforms = [];
  4703. }
  4704. getFieldMask() {
  4705. return null;
  4706. }
  4707. }
  4708. class rs extends Wn {
  4709. constructor(t, e) {
  4710. super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ ,
  4711. this.fieldTransforms = [];
  4712. }
  4713. getFieldMask() {
  4714. return null;
  4715. }
  4716. }
  4717. /**
  4718. * @license
  4719. * Copyright 2017 Google LLC
  4720. *
  4721. * Licensed under the Apache License, Version 2.0 (the "License");
  4722. * you may not use this file except in compliance with the License.
  4723. * You may obtain a copy of the License at
  4724. *
  4725. * http://www.apache.org/licenses/LICENSE-2.0
  4726. *
  4727. * Unless required by applicable law or agreed to in writing, software
  4728. * distributed under the License is distributed on an "AS IS" BASIS,
  4729. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4730. * See the License for the specific language governing permissions and
  4731. * limitations under the License.
  4732. */ class os {
  4733. // TODO(b/33078163): just use simplest form of existence filter for now
  4734. constructor(t) {
  4735. this.count = t;
  4736. }
  4737. }
  4738. /**
  4739. * @license
  4740. * Copyright 2017 Google LLC
  4741. *
  4742. * Licensed under the Apache License, Version 2.0 (the "License");
  4743. * you may not use this file except in compliance with the License.
  4744. * You may obtain a copy of the License at
  4745. *
  4746. * http://www.apache.org/licenses/LICENSE-2.0
  4747. *
  4748. * Unless required by applicable law or agreed to in writing, software
  4749. * distributed under the License is distributed on an "AS IS" BASIS,
  4750. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4751. * See the License for the specific language governing permissions and
  4752. * limitations under the License.
  4753. */
  4754. /**
  4755. * Error Codes describing the different ways GRPC can fail. These are copied
  4756. * directly from GRPC's sources here:
  4757. *
  4758. * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
  4759. *
  4760. * Important! The names of these identifiers matter because the string forms
  4761. * are used for reverse lookups from the webchannel stream. Do NOT change the
  4762. * names of these identifiers or change this into a const enum.
  4763. */ var us, cs;
  4764. /**
  4765. * Determines whether an error code represents a permanent error when received
  4766. * in response to a non-write operation.
  4767. *
  4768. * See isPermanentWriteError for classifying write errors.
  4769. */
  4770. function as(t) {
  4771. switch (t) {
  4772. default:
  4773. return O();
  4774. case B.CANCELLED:
  4775. case B.UNKNOWN:
  4776. case B.DEADLINE_EXCEEDED:
  4777. case B.RESOURCE_EXHAUSTED:
  4778. case B.INTERNAL:
  4779. case B.UNAVAILABLE:
  4780. // Unauthenticated means something went wrong with our token and we need
  4781. // to retry with new credentials which will happen automatically.
  4782. case B.UNAUTHENTICATED:
  4783. return !1;
  4784. case B.INVALID_ARGUMENT:
  4785. case B.NOT_FOUND:
  4786. case B.ALREADY_EXISTS:
  4787. case B.PERMISSION_DENIED:
  4788. case B.FAILED_PRECONDITION:
  4789. // Aborted might be retried in some scenarios, but that is dependant on
  4790. // the context and should handled individually by the calling code.
  4791. // See https://cloud.google.com/apis/design/errors.
  4792. case B.ABORTED:
  4793. case B.OUT_OF_RANGE:
  4794. case B.UNIMPLEMENTED:
  4795. case B.DATA_LOSS:
  4796. return !0;
  4797. }
  4798. }
  4799. /**
  4800. * Determines whether an error code represents a permanent error when received
  4801. * in response to a write operation.
  4802. *
  4803. * Write operations must be handled specially because as of b/119437764, ABORTED
  4804. * errors on the write stream should be retried too (even though ABORTED errors
  4805. * are not generally retryable).
  4806. *
  4807. * Note that during the initial handshake on the write stream an ABORTED error
  4808. * signals that we should discard our stream token (i.e. it is permanent). This
  4809. * means a handshake error should be classified with isPermanentError, above.
  4810. */
  4811. /**
  4812. * Maps an error Code from GRPC status code number, like 0, 1, or 14. These
  4813. * are not the same as HTTP status codes.
  4814. *
  4815. * @returns The Code equivalent to the given GRPC status code. Fails if there
  4816. * is no match.
  4817. */
  4818. function hs(t) {
  4819. if (void 0 === t)
  4820. // This shouldn't normally happen, but in certain error cases (like trying
  4821. // to send invalid proto messages) we may get an error with no GRPC code.
  4822. return x("GRPC error has no .code"), B.UNKNOWN;
  4823. switch (t) {
  4824. case us.OK:
  4825. return B.OK;
  4826. case us.CANCELLED:
  4827. return B.CANCELLED;
  4828. case us.UNKNOWN:
  4829. return B.UNKNOWN;
  4830. case us.DEADLINE_EXCEEDED:
  4831. return B.DEADLINE_EXCEEDED;
  4832. case us.RESOURCE_EXHAUSTED:
  4833. return B.RESOURCE_EXHAUSTED;
  4834. case us.INTERNAL:
  4835. return B.INTERNAL;
  4836. case us.UNAVAILABLE:
  4837. return B.UNAVAILABLE;
  4838. case us.UNAUTHENTICATED:
  4839. return B.UNAUTHENTICATED;
  4840. case us.INVALID_ARGUMENT:
  4841. return B.INVALID_ARGUMENT;
  4842. case us.NOT_FOUND:
  4843. return B.NOT_FOUND;
  4844. case us.ALREADY_EXISTS:
  4845. return B.ALREADY_EXISTS;
  4846. case us.PERMISSION_DENIED:
  4847. return B.PERMISSION_DENIED;
  4848. case us.FAILED_PRECONDITION:
  4849. return B.FAILED_PRECONDITION;
  4850. case us.ABORTED:
  4851. return B.ABORTED;
  4852. case us.OUT_OF_RANGE:
  4853. return B.OUT_OF_RANGE;
  4854. case us.UNIMPLEMENTED:
  4855. return B.UNIMPLEMENTED;
  4856. case us.DATA_LOSS:
  4857. return B.DATA_LOSS;
  4858. default:
  4859. return O();
  4860. }
  4861. }
  4862. /**
  4863. * Converts an HTTP response's error status to the equivalent error code.
  4864. *
  4865. * @param status - An HTTP error response status ("FAILED_PRECONDITION",
  4866. * "UNKNOWN", etc.)
  4867. * @returns The equivalent Code. Non-matching responses are mapped to
  4868. * Code.UNKNOWN.
  4869. */ (cs = us || (us = {}))[cs.OK = 0] = "OK", cs[cs.CANCELLED = 1] = "CANCELLED",
  4870. cs[cs.UNKNOWN = 2] = "UNKNOWN", cs[cs.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT",
  4871. cs[cs.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", cs[cs.NOT_FOUND = 5] = "NOT_FOUND",
  4872. cs[cs.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", cs[cs.PERMISSION_DENIED = 7] = "PERMISSION_DENIED",
  4873. cs[cs.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", cs[cs.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED",
  4874. cs[cs.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", cs[cs.ABORTED = 10] = "ABORTED",
  4875. cs[cs.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", cs[cs.UNIMPLEMENTED = 12] = "UNIMPLEMENTED",
  4876. cs[cs.INTERNAL = 13] = "INTERNAL", cs[cs.UNAVAILABLE = 14] = "UNAVAILABLE", cs[cs.DATA_LOSS = 15] = "DATA_LOSS";
  4877. /**
  4878. * @license
  4879. * Copyright 2017 Google LLC
  4880. *
  4881. * Licensed under the Apache License, Version 2.0 (the "License");
  4882. * you may not use this file except in compliance with the License.
  4883. * You may obtain a copy of the License at
  4884. *
  4885. * http://www.apache.org/licenses/LICENSE-2.0
  4886. *
  4887. * Unless required by applicable law or agreed to in writing, software
  4888. * distributed under the License is distributed on an "AS IS" BASIS,
  4889. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4890. * See the License for the specific language governing permissions and
  4891. * limitations under the License.
  4892. */
  4893. /**
  4894. * A map implementation that uses objects as keys. Objects must have an
  4895. * associated equals function and must be immutable. Entries in the map are
  4896. * stored together with the key being produced from the mapKeyFn. This map
  4897. * automatically handles collisions of keys.
  4898. */
  4899. class ls {
  4900. constructor(t, e) {
  4901. this.mapKeyFn = t, this.equalsFn = e,
  4902. /**
  4903. * The inner map for a key/value pair. Due to the possibility of collisions we
  4904. * keep a list of entries that we do a linear search through to find an actual
  4905. * match. Note that collisions should be rare, so we still expect near
  4906. * constant time lookups in practice.
  4907. */
  4908. this.inner = {},
  4909. /** The number of entries stored in the map */
  4910. this.innerSize = 0;
  4911. }
  4912. /** Get a value for this key, or undefined if it does not exist. */ get(t) {
  4913. const e = this.mapKeyFn(t), n = this.inner[e];
  4914. if (void 0 !== n) for (const [e, s] of n) if (this.equalsFn(e, t)) return s;
  4915. }
  4916. has(t) {
  4917. return void 0 !== this.get(t);
  4918. }
  4919. /** Put this key and value in the map. */ set(t, e) {
  4920. const n = this.mapKeyFn(t), s = this.inner[n];
  4921. if (void 0 === s) return this.inner[n] = [ [ t, e ] ], void this.innerSize++;
  4922. for (let n = 0; n < s.length; n++) if (this.equalsFn(s[n][0], t))
  4923. // This is updating an existing entry and does not increase `innerSize`.
  4924. return void (s[n] = [ t, e ]);
  4925. s.push([ t, e ]), this.innerSize++;
  4926. }
  4927. /**
  4928. * Remove this key from the map. Returns a boolean if anything was deleted.
  4929. */ delete(t) {
  4930. const e = this.mapKeyFn(t), n = this.inner[e];
  4931. if (void 0 === n) return !1;
  4932. for (let s = 0; s < n.length; s++) if (this.equalsFn(n[s][0], t)) return 1 === n.length ? delete this.inner[e] : n.splice(s, 1),
  4933. this.innerSize--, !0;
  4934. return !1;
  4935. }
  4936. forEach(t) {
  4937. Bt(this.inner, ((e, n) => {
  4938. for (const [e, s] of n) t(e, s);
  4939. }));
  4940. }
  4941. isEmpty() {
  4942. return Lt(this.inner);
  4943. }
  4944. size() {
  4945. return this.innerSize;
  4946. }
  4947. }
  4948. /**
  4949. * @license
  4950. * Copyright 2017 Google LLC
  4951. *
  4952. * Licensed under the Apache License, Version 2.0 (the "License");
  4953. * you may not use this file except in compliance with the License.
  4954. * You may obtain a copy of the License at
  4955. *
  4956. * http://www.apache.org/licenses/LICENSE-2.0
  4957. *
  4958. * Unless required by applicable law or agreed to in writing, software
  4959. * distributed under the License is distributed on an "AS IS" BASIS,
  4960. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4961. * See the License for the specific language governing permissions and
  4962. * limitations under the License.
  4963. */ const fs = new Ge(ct.comparator);
  4964. function ds() {
  4965. return fs;
  4966. }
  4967. const _s = new Ge(ct.comparator);
  4968. function ws(...t) {
  4969. let e = _s;
  4970. for (const n of t) e = e.insert(n.key, n);
  4971. return e;
  4972. }
  4973. function ms(t) {
  4974. let e = _s;
  4975. return t.forEach(((t, n) => e = e.insert(t, n.overlayedDocument))), e;
  4976. }
  4977. function gs() {
  4978. return ps();
  4979. }
  4980. function ys() {
  4981. return ps();
  4982. }
  4983. function ps() {
  4984. return new ls((t => t.toString()), ((t, e) => t.isEqual(e)));
  4985. }
  4986. const Is = new Ge(ct.comparator);
  4987. const Ts = new We(ct.comparator);
  4988. function Es(...t) {
  4989. let e = Ts;
  4990. for (const n of t) e = e.add(n);
  4991. return e;
  4992. }
  4993. const As = new We(Z);
  4994. function Rs() {
  4995. return As;
  4996. }
  4997. /**
  4998. * @license
  4999. * Copyright 2017 Google LLC
  5000. *
  5001. * Licensed under the Apache License, Version 2.0 (the "License");
  5002. * you may not use this file except in compliance with the License.
  5003. * You may obtain a copy of the License at
  5004. *
  5005. * http://www.apache.org/licenses/LICENSE-2.0
  5006. *
  5007. * Unless required by applicable law or agreed to in writing, software
  5008. * distributed under the License is distributed on an "AS IS" BASIS,
  5009. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5010. * See the License for the specific language governing permissions and
  5011. * limitations under the License.
  5012. */
  5013. /**
  5014. * An event from the RemoteStore. It is split into targetChanges (changes to the
  5015. * state or the set of documents in our watched targets) and documentUpdates
  5016. * (changes to the actual documents).
  5017. */ class bs {
  5018. constructor(
  5019. /**
  5020. * The snapshot version this event brings us up to, or MIN if not set.
  5021. */
  5022. t,
  5023. /**
  5024. * A map from target to changes to the target. See TargetChange.
  5025. */
  5026. e,
  5027. /**
  5028. * A set of targets that is known to be inconsistent. Listens for these
  5029. * targets should be re-established without resume tokens.
  5030. */
  5031. n,
  5032. /**
  5033. * A set of which documents have changed or been deleted, along with the
  5034. * doc's new values (if not deleted).
  5035. */
  5036. s,
  5037. /**
  5038. * A set of which document updates are due only to limbo resolution targets.
  5039. */
  5040. i) {
  5041. this.snapshotVersion = t, this.targetChanges = e, this.targetMismatches = n, this.documentUpdates = s,
  5042. this.resolvedLimboDocuments = i;
  5043. }
  5044. /**
  5045. * HACK: Views require RemoteEvents in order to determine whether the view is
  5046. * CURRENT, but secondary tabs don't receive remote events. So this method is
  5047. * used to create a synthesized RemoteEvent that can be used to apply a
  5048. * CURRENT status change to a View, for queries executed in a different tab.
  5049. */
  5050. // PORTING NOTE: Multi-tab only
  5051. static createSynthesizedRemoteEventForCurrentChange(t, e, n) {
  5052. const s = new Map;
  5053. return s.set(t, Ps.createSynthesizedTargetChangeForCurrentChange(t, e, n)), new bs(st.min(), s, Rs(), ds(), Es());
  5054. }
  5055. }
  5056. /**
  5057. * A TargetChange specifies the set of changes for a specific target as part of
  5058. * a RemoteEvent. These changes track which documents are added, modified or
  5059. * removed, as well as the target's resume token and whether the target is
  5060. * marked CURRENT.
  5061. * The actual changes *to* documents are not part of the TargetChange since
  5062. * documents may be part of multiple targets.
  5063. */ class Ps {
  5064. constructor(
  5065. /**
  5066. * An opaque, server-assigned token that allows watching a query to be resumed
  5067. * after disconnecting without retransmitting all the data that matches the
  5068. * query. The resume token essentially identifies a point in time from which
  5069. * the server should resume sending results.
  5070. */
  5071. t,
  5072. /**
  5073. * The "current" (synced) status of this target. Note that "current"
  5074. * has special meaning in the RPC protocol that implies that a target is
  5075. * both up-to-date and consistent with the rest of the watch stream.
  5076. */
  5077. e,
  5078. /**
  5079. * The set of documents that were newly assigned to this target as part of
  5080. * this remote event.
  5081. */
  5082. n,
  5083. /**
  5084. * The set of documents that were already assigned to this target but received
  5085. * an update during this remote event.
  5086. */
  5087. s,
  5088. /**
  5089. * The set of documents that were removed from this target as part of this
  5090. * remote event.
  5091. */
  5092. i) {
  5093. this.resumeToken = t, this.current = e, this.addedDocuments = n, this.modifiedDocuments = s,
  5094. this.removedDocuments = i;
  5095. }
  5096. /**
  5097. * This method is used to create a synthesized TargetChanges that can be used to
  5098. * apply a CURRENT status change to a View (for queries executed in a different
  5099. * tab) or for new queries (to raise snapshots with correct CURRENT status).
  5100. */ static createSynthesizedTargetChangeForCurrentChange(t, e, n) {
  5101. return new Ps(n, e, Es(), Es(), Es());
  5102. }
  5103. }
  5104. /**
  5105. * @license
  5106. * Copyright 2017 Google LLC
  5107. *
  5108. * Licensed under the Apache License, Version 2.0 (the "License");
  5109. * you may not use this file except in compliance with the License.
  5110. * You may obtain a copy of the License at
  5111. *
  5112. * http://www.apache.org/licenses/LICENSE-2.0
  5113. *
  5114. * Unless required by applicable law or agreed to in writing, software
  5115. * distributed under the License is distributed on an "AS IS" BASIS,
  5116. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5117. * See the License for the specific language governing permissions and
  5118. * limitations under the License.
  5119. */
  5120. /**
  5121. * Represents a changed document and a list of target ids to which this change
  5122. * applies.
  5123. *
  5124. * If document has been deleted NoDocument will be provided.
  5125. */ class vs {
  5126. constructor(
  5127. /** The new document applies to all of these targets. */
  5128. t,
  5129. /** The new document is removed from all of these targets. */
  5130. e,
  5131. /** The key of the document for this change. */
  5132. n,
  5133. /**
  5134. * The new document or NoDocument if it was deleted. Is null if the
  5135. * document went out of view without the server sending a new document.
  5136. */
  5137. s) {
  5138. this.It = t, this.removedTargetIds = e, this.key = n, this.Tt = s;
  5139. }
  5140. }
  5141. class Vs {
  5142. constructor(t, e) {
  5143. this.targetId = t, this.Et = e;
  5144. }
  5145. }
  5146. class Ss {
  5147. constructor(
  5148. /** What kind of change occurred to the watch target. */
  5149. t,
  5150. /** The target IDs that were added/removed/set. */
  5151. e,
  5152. /**
  5153. * An opaque, server-assigned token that allows watching a target to be
  5154. * resumed after disconnecting without retransmitting all the data that
  5155. * matches the target. The resume token essentially identifies a point in
  5156. * time from which the server should resume sending results.
  5157. */
  5158. n = Qt.EMPTY_BYTE_STRING
  5159. /** An RPC error indicating why the watch failed. */ , s = null) {
  5160. this.state = t, this.targetIds = e, this.resumeToken = n, this.cause = s;
  5161. }
  5162. }
  5163. /** Tracks the internal state of a Watch target. */ class Ds {
  5164. constructor() {
  5165. /**
  5166. * The number of pending responses (adds or removes) that we are waiting on.
  5167. * We only consider targets active that have no pending responses.
  5168. */
  5169. this.At = 0,
  5170. /**
  5171. * Keeps track of the document changes since the last raised snapshot.
  5172. *
  5173. * These changes are continuously updated as we receive document updates and
  5174. * always reflect the current set of changes against the last issued snapshot.
  5175. */
  5176. this.Rt = Ns(),
  5177. /** See public getters for explanations of these fields. */
  5178. this.bt = Qt.EMPTY_BYTE_STRING, this.Pt = !1,
  5179. /**
  5180. * Whether this target state should be included in the next snapshot. We
  5181. * initialize to true so that newly-added targets are included in the next
  5182. * RemoteEvent.
  5183. */
  5184. this.vt = !0;
  5185. }
  5186. /**
  5187. * Whether this target has been marked 'current'.
  5188. *
  5189. * 'Current' has special meaning in the RPC protocol: It implies that the
  5190. * Watch backend has sent us all changes up to the point at which the target
  5191. * was added and that the target is consistent with the rest of the watch
  5192. * stream.
  5193. */ get current() {
  5194. return this.Pt;
  5195. }
  5196. /** The last resume token sent to us for this target. */ get resumeToken() {
  5197. return this.bt;
  5198. }
  5199. /** Whether this target has pending target adds or target removes. */ get Vt() {
  5200. return 0 !== this.At;
  5201. }
  5202. /** Whether we have modified any state that should trigger a snapshot. */ get St() {
  5203. return this.vt;
  5204. }
  5205. /**
  5206. * Applies the resume token to the TargetChange, but only when it has a new
  5207. * value. Empty resumeTokens are discarded.
  5208. */ Dt(t) {
  5209. t.approximateByteSize() > 0 && (this.vt = !0, this.bt = t);
  5210. }
  5211. /**
  5212. * Creates a target change from the current set of changes.
  5213. *
  5214. * To reset the document changes after raising this snapshot, call
  5215. * `clearPendingChanges()`.
  5216. */ Ct() {
  5217. let t = Es(), e = Es(), n = Es();
  5218. return this.Rt.forEach(((s, i) => {
  5219. switch (i) {
  5220. case 0 /* ChangeType.Added */ :
  5221. t = t.add(s);
  5222. break;
  5223. case 2 /* ChangeType.Modified */ :
  5224. e = e.add(s);
  5225. break;
  5226. case 1 /* ChangeType.Removed */ :
  5227. n = n.add(s);
  5228. break;
  5229. default:
  5230. O();
  5231. }
  5232. })), new Ps(this.bt, this.Pt, t, e, n);
  5233. }
  5234. /**
  5235. * Resets the document changes and sets `hasPendingChanges` to false.
  5236. */ xt() {
  5237. this.vt = !1, this.Rt = Ns();
  5238. }
  5239. Nt(t, e) {
  5240. this.vt = !0, this.Rt = this.Rt.insert(t, e);
  5241. }
  5242. kt(t) {
  5243. this.vt = !0, this.Rt = this.Rt.remove(t);
  5244. }
  5245. Ot() {
  5246. this.At += 1;
  5247. }
  5248. Mt() {
  5249. this.At -= 1;
  5250. }
  5251. Ft() {
  5252. this.vt = !0, this.Pt = !0;
  5253. }
  5254. }
  5255. /**
  5256. * A helper class to accumulate watch changes into a RemoteEvent.
  5257. */
  5258. class Cs {
  5259. constructor(t) {
  5260. this.$t = t,
  5261. /** The internal state of all tracked targets. */
  5262. this.Bt = new Map,
  5263. /** Keeps track of the documents to update since the last raised snapshot. */
  5264. this.Lt = ds(),
  5265. /** A mapping of document keys to their set of target IDs. */
  5266. this.qt = xs(),
  5267. /**
  5268. * A list of targets with existence filter mismatches. These targets are
  5269. * known to be inconsistent and their listens needs to be re-established by
  5270. * RemoteStore.
  5271. */
  5272. this.Ut = new We(Z);
  5273. }
  5274. /**
  5275. * Processes and adds the DocumentWatchChange to the current set of changes.
  5276. */ Kt(t) {
  5277. for (const e of t.It) t.Tt && t.Tt.isFoundDocument() ? this.Gt(e, t.Tt) : this.Qt(e, t.key, t.Tt);
  5278. for (const e of t.removedTargetIds) this.Qt(e, t.key, t.Tt);
  5279. }
  5280. /** Processes and adds the WatchTargetChange to the current set of changes. */ jt(t) {
  5281. this.forEachTarget(t, (e => {
  5282. const n = this.Wt(e);
  5283. switch (t.state) {
  5284. case 0 /* WatchTargetChangeState.NoChange */ :
  5285. this.zt(e) && n.Dt(t.resumeToken);
  5286. break;
  5287. case 1 /* WatchTargetChangeState.Added */ :
  5288. // We need to decrement the number of pending acks needed from watch
  5289. // for this targetId.
  5290. n.Mt(), n.Vt ||
  5291. // We have a freshly added target, so we need to reset any state
  5292. // that we had previously. This can happen e.g. when remove and add
  5293. // back a target for existence filter mismatches.
  5294. n.xt(), n.Dt(t.resumeToken);
  5295. break;
  5296. case 2 /* WatchTargetChangeState.Removed */ :
  5297. // We need to keep track of removed targets to we can post-filter and
  5298. // remove any target changes.
  5299. // We need to decrement the number of pending acks needed from watch
  5300. // for this targetId.
  5301. n.Mt(), n.Vt || this.removeTarget(e);
  5302. break;
  5303. case 3 /* WatchTargetChangeState.Current */ :
  5304. this.zt(e) && (n.Ft(), n.Dt(t.resumeToken));
  5305. break;
  5306. case 4 /* WatchTargetChangeState.Reset */ :
  5307. this.zt(e) && (
  5308. // Reset the target and synthesizes removes for all existing
  5309. // documents. The backend will re-add any documents that still
  5310. // match the target before it sends the next global snapshot.
  5311. this.Ht(e), n.Dt(t.resumeToken));
  5312. break;
  5313. default:
  5314. O();
  5315. }
  5316. }));
  5317. }
  5318. /**
  5319. * Iterates over all targetIds that the watch change applies to: either the
  5320. * targetIds explicitly listed in the change or the targetIds of all currently
  5321. * active targets.
  5322. */ forEachTarget(t, e) {
  5323. t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.Bt.forEach(((t, n) => {
  5324. this.zt(n) && e(n);
  5325. }));
  5326. }
  5327. /**
  5328. * Handles existence filters and synthesizes deletes for filter mismatches.
  5329. * Targets that are invalidated by filter mismatches are added to
  5330. * `pendingTargetResets`.
  5331. */ Jt(t) {
  5332. const e = t.targetId, n = t.Et.count, s = this.Yt(e);
  5333. if (s) {
  5334. const t = s.target;
  5335. if (rn(t)) if (0 === n) {
  5336. // The existence filter told us the document does not exist. We deduce
  5337. // that this document does not exist and apply a deleted document to
  5338. // our updates. Without applying this deleted document there might be
  5339. // another query that will raise this document as part of a snapshot
  5340. // until it is resolved, essentially exposing inconsistency between
  5341. // queries.
  5342. const n = new ct(t.path);
  5343. this.Qt(e, n, Ze.newNoDocument(n, st.min()));
  5344. } else M(1 === n); else {
  5345. this.Xt(e) !== n && (
  5346. // Existence filter mismatch: We reset the mapping and raise a new
  5347. // snapshot with `isFromCache:true`.
  5348. this.Ht(e), this.Ut = this.Ut.add(e));
  5349. }
  5350. }
  5351. }
  5352. /**
  5353. * Converts the currently accumulated state into a remote event at the
  5354. * provided snapshot version. Resets the accumulated changes before returning.
  5355. */ Zt(t) {
  5356. const e = new Map;
  5357. this.Bt.forEach(((n, s) => {
  5358. const i = this.Yt(s);
  5359. if (i) {
  5360. if (n.current && rn(i.target)) {
  5361. // Document queries for document that don't exist can produce an empty
  5362. // result set. To update our local cache, we synthesize a document
  5363. // delete if we have not previously received the document. This
  5364. // resolves the limbo state of the document, removing it from
  5365. // limboDocumentRefs.
  5366. // TODO(dimond): Ideally we would have an explicit lookup target
  5367. // instead resulting in an explicit delete message and we could
  5368. // remove this special logic.
  5369. const e = new ct(i.target.path);
  5370. null !== this.Lt.get(e) || this.te(s, e) || this.Qt(s, e, Ze.newNoDocument(e, t));
  5371. }
  5372. n.St && (e.set(s, n.Ct()), n.xt());
  5373. }
  5374. }));
  5375. let n = Es();
  5376. // We extract the set of limbo-only document updates as the GC logic
  5377. // special-cases documents that do not appear in the target cache.
  5378. // TODO(gsoltis): Expand on this comment once GC is available in the JS
  5379. // client.
  5380. this.qt.forEach(((t, e) => {
  5381. let s = !0;
  5382. e.forEachWhile((t => {
  5383. const e = this.Yt(t);
  5384. return !e || 2 /* TargetPurpose.LimboResolution */ === e.purpose || (s = !1, !1);
  5385. })), s && (n = n.add(t));
  5386. })), this.Lt.forEach(((e, n) => n.setReadTime(t)));
  5387. const s = new bs(t, e, this.Ut, this.Lt, n);
  5388. return this.Lt = ds(), this.qt = xs(), this.Ut = new We(Z), s;
  5389. }
  5390. /**
  5391. * Adds the provided document to the internal list of document updates and
  5392. * its document key to the given target's mapping.
  5393. */
  5394. // Visible for testing.
  5395. Gt(t, e) {
  5396. if (!this.zt(t)) return;
  5397. const n = this.te(t, e.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */;
  5398. 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));
  5399. }
  5400. /**
  5401. * Removes the provided document from the target mapping. If the
  5402. * document no longer matches the target, but the document's state is still
  5403. * known (e.g. we know that the document was deleted or we received the change
  5404. * that caused the filter mismatch), the new document can be provided
  5405. * to update the remote document cache.
  5406. */
  5407. // Visible for testing.
  5408. Qt(t, e, n) {
  5409. if (!this.zt(t)) return;
  5410. const s = this.Wt(t);
  5411. this.te(t, e) ? s.Nt(e, 1 /* ChangeType.Removed */) :
  5412. // The document may have entered and left the target before we raised a
  5413. // snapshot, so we can just ignore the change.
  5414. s.kt(e), this.qt = this.qt.insert(e, this.ee(e).delete(t)), n && (this.Lt = this.Lt.insert(e, n));
  5415. }
  5416. removeTarget(t) {
  5417. this.Bt.delete(t);
  5418. }
  5419. /**
  5420. * Returns the current count of documents in the target. This includes both
  5421. * the number of documents that the LocalStore considers to be part of the
  5422. * target as well as any accumulated changes.
  5423. */ Xt(t) {
  5424. const e = this.Wt(t).Ct();
  5425. return this.$t.getRemoteKeysForTarget(t).size + e.addedDocuments.size - e.removedDocuments.size;
  5426. }
  5427. /**
  5428. * Increment the number of acks needed from watch before we can consider the
  5429. * server to be 'in-sync' with the client's active targets.
  5430. */ Ot(t) {
  5431. this.Wt(t).Ot();
  5432. }
  5433. Wt(t) {
  5434. let e = this.Bt.get(t);
  5435. return e || (e = new Ds, this.Bt.set(t, e)), e;
  5436. }
  5437. ee(t) {
  5438. let e = this.qt.get(t);
  5439. return e || (e = new We(Z), this.qt = this.qt.insert(t, e)), e;
  5440. }
  5441. /**
  5442. * Verifies that the user is still interested in this target (by calling
  5443. * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs
  5444. * from watch.
  5445. */ zt(t) {
  5446. const e = null !== this.Yt(t);
  5447. return e || C("WatchChangeAggregator", "Detected inactive target", t), e;
  5448. }
  5449. /**
  5450. * Returns the TargetData for an active target (i.e. a target that the user
  5451. * is still interested in that has no outstanding target change requests).
  5452. */ Yt(t) {
  5453. const e = this.Bt.get(t);
  5454. return e && e.Vt ? null : this.$t.ne(t);
  5455. }
  5456. /**
  5457. * Resets the state of a Watch target to its initial state (e.g. sets
  5458. * 'current' to false, clears the resume token and removes its target mapping
  5459. * from all documents).
  5460. */ Ht(t) {
  5461. this.Bt.set(t, new Ds);
  5462. this.$t.getRemoteKeysForTarget(t).forEach((e => {
  5463. this.Qt(t, e, /*updatedDocument=*/ null);
  5464. }));
  5465. }
  5466. /**
  5467. * Returns whether the LocalStore considers the document to be part of the
  5468. * specified target.
  5469. */ te(t, e) {
  5470. return this.$t.getRemoteKeysForTarget(t).has(e);
  5471. }
  5472. }
  5473. function xs() {
  5474. return new Ge(ct.comparator);
  5475. }
  5476. function Ns() {
  5477. return new Ge(ct.comparator);
  5478. }
  5479. /**
  5480. * @license
  5481. * Copyright 2017 Google LLC
  5482. *
  5483. * Licensed under the Apache License, Version 2.0 (the "License");
  5484. * you may not use this file except in compliance with the License.
  5485. * You may obtain a copy of the License at
  5486. *
  5487. * http://www.apache.org/licenses/LICENSE-2.0
  5488. *
  5489. * Unless required by applicable law or agreed to in writing, software
  5490. * distributed under the License is distributed on an "AS IS" BASIS,
  5491. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5492. * See the License for the specific language governing permissions and
  5493. * limitations under the License.
  5494. */ const ks = (() => {
  5495. const t = {
  5496. asc: "ASCENDING",
  5497. desc: "DESCENDING"
  5498. };
  5499. return t;
  5500. })(), Os = (() => {
  5501. const t = {
  5502. "<": "LESS_THAN",
  5503. "<=": "LESS_THAN_OR_EQUAL",
  5504. ">": "GREATER_THAN",
  5505. ">=": "GREATER_THAN_OR_EQUAL",
  5506. "==": "EQUAL",
  5507. "!=": "NOT_EQUAL",
  5508. "array-contains": "ARRAY_CONTAINS",
  5509. in: "IN",
  5510. "not-in": "NOT_IN",
  5511. "array-contains-any": "ARRAY_CONTAINS_ANY"
  5512. };
  5513. return t;
  5514. })(), Ms = (() => {
  5515. const t = {
  5516. and: "AND",
  5517. or: "OR"
  5518. };
  5519. return t;
  5520. })();
  5521. /**
  5522. * This class generates JsonObject values for the Datastore API suitable for
  5523. * sending to either GRPC stub methods or via the JSON/HTTP REST API.
  5524. *
  5525. * The serializer supports both Protobuf.js and Proto3 JSON formats. By
  5526. * setting `useProto3Json` to true, the serializer will use the Proto3 JSON
  5527. * format.
  5528. *
  5529. * For a description of the Proto3 JSON format check
  5530. * https://developers.google.com/protocol-buffers/docs/proto3#json
  5531. *
  5532. * TODO(klimt): We can remove the databaseId argument if we keep the full
  5533. * resource name in documents.
  5534. */
  5535. class Fs {
  5536. constructor(t, e) {
  5537. this.databaseId = t, this.wt = e;
  5538. }
  5539. }
  5540. /**
  5541. * Returns a value for a Date that's appropriate to put into a proto.
  5542. */
  5543. function $s(t, e) {
  5544. if (t.wt) {
  5545. return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`;
  5546. }
  5547. return {
  5548. seconds: "" + e.seconds,
  5549. nanos: e.nanoseconds
  5550. };
  5551. }
  5552. /**
  5553. * Returns a value for bytes that's appropriate to put in a proto.
  5554. *
  5555. * Visible for testing.
  5556. */
  5557. function Bs(t, e) {
  5558. return t.wt ? e.toBase64() : e.toUint8Array();
  5559. }
  5560. /**
  5561. * Returns a ByteString based on the proto string value.
  5562. */ function Ls(t, e) {
  5563. return $s(t, e.toTimestamp());
  5564. }
  5565. function qs(t) {
  5566. return M(!!t), st.fromTimestamp(function(t) {
  5567. const e = Wt(t);
  5568. return new nt(e.seconds, e.nanos);
  5569. }(t));
  5570. }
  5571. function Us(t, e) {
  5572. return function(t) {
  5573. return new rt([ "projects", t.projectId, "databases", t.database ]);
  5574. }(t).child("documents").child(e).canonicalString();
  5575. }
  5576. function Ks(t) {
  5577. const e = rt.fromString(t);
  5578. return M(wi(e)), e;
  5579. }
  5580. function Gs(t, e) {
  5581. return Us(t.databaseId, e.path);
  5582. }
  5583. function Qs(t, e) {
  5584. const n = Ks(e);
  5585. if (n.get(1) !== t.databaseId.projectId) throw new L(B.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n.get(1) + " vs " + t.databaseId.projectId);
  5586. if (n.get(3) !== t.databaseId.database) throw new L(B.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n.get(3) + " vs " + t.databaseId.database);
  5587. return new ct(Hs(n));
  5588. }
  5589. function js(t, e) {
  5590. return Us(t.databaseId, e);
  5591. }
  5592. function Ws(t) {
  5593. const e = Ks(t);
  5594. // In v1beta1 queries for collections at the root did not have a trailing
  5595. // "/documents". In v1 all resource paths contain "/documents". Preserve the
  5596. // ability to read the v1beta1 form for compatibility with queries persisted
  5597. // in the local target cache.
  5598. return 4 === e.length ? rt.emptyPath() : Hs(e);
  5599. }
  5600. function zs(t) {
  5601. return new rt([ "projects", t.databaseId.projectId, "databases", t.databaseId.database ]).canonicalString();
  5602. }
  5603. function Hs(t) {
  5604. return M(t.length > 4 && "documents" === t.get(4)), t.popFirst(5);
  5605. }
  5606. /** Creates a Document proto from key and fields (but no create/update time) */ function Js(t, e, n) {
  5607. return {
  5608. name: Gs(t, e),
  5609. fields: n.value.mapValue.fields
  5610. };
  5611. }
  5612. function Ys(t, e, n) {
  5613. const s = Qs(t, e.name), i = qs(e.updateTime), r = e.createTime ? qs(e.createTime) : st.min(), o = new Ye({
  5614. mapValue: {
  5615. fields: e.fields
  5616. }
  5617. }), u = Ze.newFoundDocument(s, i, r, o);
  5618. return n && u.setHasCommittedMutations(), n ? u.setHasCommittedMutations() : u;
  5619. }
  5620. function Xs(t, e) {
  5621. return "found" in e ? function(t, e) {
  5622. M(!!e.found), e.found.name, e.found.updateTime;
  5623. const n = Qs(t, e.found.name), s = qs(e.found.updateTime), i = e.found.createTime ? qs(e.found.createTime) : st.min(), r = new Ye({
  5624. mapValue: {
  5625. fields: e.found.fields
  5626. }
  5627. });
  5628. return Ze.newFoundDocument(n, s, i, r);
  5629. }(t, e) : "missing" in e ? function(t, e) {
  5630. M(!!e.missing), M(!!e.readTime);
  5631. const n = Qs(t, e.missing), s = qs(e.readTime);
  5632. return Ze.newNoDocument(n, s);
  5633. }(t, e) : O();
  5634. }
  5635. function Zs(t, e) {
  5636. let n;
  5637. if ("targetChange" in e) {
  5638. e.targetChange;
  5639. // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'
  5640. // if unset
  5641. const s = function(t) {
  5642. 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 */ : O();
  5643. }(e.targetChange.targetChangeType || "NO_CHANGE"), i = e.targetChange.targetIds || [], r = function(t, e) {
  5644. return t.wt ? (M(void 0 === e || "string" == typeof e), Qt.fromBase64String(e || "")) : (M(void 0 === e || e instanceof Uint8Array),
  5645. Qt.fromUint8Array(e || new Uint8Array));
  5646. }(t, e.targetChange.resumeToken), o = e.targetChange.cause, u = o && function(t) {
  5647. const e = void 0 === t.code ? B.UNKNOWN : hs(t.code);
  5648. return new L(e, t.message || "");
  5649. }
  5650. /**
  5651. * Returns a value for a number (or null) that's appropriate to put into
  5652. * a google.protobuf.Int32Value proto.
  5653. * DO NOT USE THIS FOR ANYTHING ELSE.
  5654. * This method cheats. It's typed as returning "number" because that's what
  5655. * our generated proto interfaces say Int32Value must be. But GRPC actually
  5656. * expects a { value: <number> } struct.
  5657. */ (o);
  5658. n = new Ss(s, i, r, u || null);
  5659. } else if ("documentChange" in e) {
  5660. e.documentChange;
  5661. const s = e.documentChange;
  5662. s.document, s.document.name, s.document.updateTime;
  5663. const i = Qs(t, s.document.name), r = qs(s.document.updateTime), o = s.document.createTime ? qs(s.document.createTime) : st.min(), u = new Ye({
  5664. mapValue: {
  5665. fields: s.document.fields
  5666. }
  5667. }), c = Ze.newFoundDocument(i, r, o, u), a = s.targetIds || [], h = s.removedTargetIds || [];
  5668. n = new vs(a, h, c.key, c);
  5669. } else if ("documentDelete" in e) {
  5670. e.documentDelete;
  5671. const s = e.documentDelete;
  5672. s.document;
  5673. const i = Qs(t, s.document), r = s.readTime ? qs(s.readTime) : st.min(), o = Ze.newNoDocument(i, r), u = s.removedTargetIds || [];
  5674. n = new vs([], u, o.key, o);
  5675. } else if ("documentRemove" in e) {
  5676. e.documentRemove;
  5677. const s = e.documentRemove;
  5678. s.document;
  5679. const i = Qs(t, s.document), r = s.removedTargetIds || [];
  5680. n = new vs([], r, i, null);
  5681. } else {
  5682. if (!("filter" in e)) return O();
  5683. {
  5684. e.filter;
  5685. const t = e.filter;
  5686. t.targetId;
  5687. const s = t.count || 0, i = new os(s), r = t.targetId;
  5688. n = new Vs(r, i);
  5689. }
  5690. }
  5691. return n;
  5692. }
  5693. function ti(t, e) {
  5694. let n;
  5695. if (e instanceof Zn) n = {
  5696. update: Js(t, e.key, e.value)
  5697. }; else if (e instanceof is) n = {
  5698. delete: Gs(t, e.key)
  5699. }; else if (e instanceof ts) n = {
  5700. update: Js(t, e.key, e.data),
  5701. updateMask: _i(e.fieldMask)
  5702. }; else {
  5703. if (!(e instanceof rs)) return O();
  5704. n = {
  5705. verify: Gs(t, e.key)
  5706. };
  5707. }
  5708. return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((t => function(t, e) {
  5709. const n = e.transform;
  5710. if (n instanceof kn) return {
  5711. fieldPath: e.field.canonicalString(),
  5712. setToServerValue: "REQUEST_TIME"
  5713. };
  5714. if (n instanceof On) return {
  5715. fieldPath: e.field.canonicalString(),
  5716. appendMissingElements: {
  5717. values: n.elements
  5718. }
  5719. };
  5720. if (n instanceof Fn) return {
  5721. fieldPath: e.field.canonicalString(),
  5722. removeAllFromArray: {
  5723. values: n.elements
  5724. }
  5725. };
  5726. if (n instanceof Bn) return {
  5727. fieldPath: e.field.canonicalString(),
  5728. increment: n.gt
  5729. };
  5730. throw O();
  5731. }(0, t)))), e.precondition.isNone || (n.currentDocument = function(t, e) {
  5732. return void 0 !== e.updateTime ? {
  5733. updateTime: Ls(t, e.updateTime)
  5734. } : void 0 !== e.exists ? {
  5735. exists: e.exists
  5736. } : O();
  5737. }(t, e.precondition)), n;
  5738. }
  5739. function ei(t, e) {
  5740. const n = e.currentDocument ? function(t) {
  5741. return void 0 !== t.updateTime ? Qn.updateTime(qs(t.updateTime)) : void 0 !== t.exists ? Qn.exists(t.exists) : Qn.none();
  5742. }(e.currentDocument) : Qn.none(), s = e.updateTransforms ? e.updateTransforms.map((e => function(t, e) {
  5743. let n = null;
  5744. if ("setToServerValue" in e) M("REQUEST_TIME" === e.setToServerValue), n = new kn; else if ("appendMissingElements" in e) {
  5745. const t = e.appendMissingElements.values || [];
  5746. n = new On(t);
  5747. } else if ("removeAllFromArray" in e) {
  5748. const t = e.removeAllFromArray.values || [];
  5749. n = new Fn(t);
  5750. } else "increment" in e ? n = new Bn(t, e.increment) : O();
  5751. const s = ut.fromServerFormat(e.fieldPath);
  5752. return new Un(s, n);
  5753. }(t, e))) : [];
  5754. if (e.update) {
  5755. e.update.name;
  5756. const i = Qs(t, e.update.name), r = new Ye({
  5757. mapValue: {
  5758. fields: e.update.fields
  5759. }
  5760. });
  5761. if (e.updateMask) {
  5762. const t = function(t) {
  5763. const e = t.fieldPaths || [];
  5764. return new Je(e.map((t => ut.fromServerFormat(t))));
  5765. }(e.updateMask);
  5766. return new ts(i, r, t, n, s);
  5767. }
  5768. return new Zn(i, r, n, s);
  5769. }
  5770. if (e.delete) {
  5771. const s = Qs(t, e.delete);
  5772. return new is(s, n);
  5773. }
  5774. if (e.verify) {
  5775. const s = Qs(t, e.verify);
  5776. return new rs(s, n);
  5777. }
  5778. return O();
  5779. }
  5780. function ni(t, e) {
  5781. return t && t.length > 0 ? (M(void 0 !== e), t.map((t => function(t, e) {
  5782. // NOTE: Deletes don't have an updateTime.
  5783. let n = t.updateTime ? qs(t.updateTime) : qs(e);
  5784. return n.isEqual(st.min()) && (
  5785. // The Firestore Emulator currently returns an update time of 0 for
  5786. // deletes of non-existing documents (rather than null). This breaks the
  5787. // test "get deleted doc while offline with source=cache" as NoDocuments
  5788. // with version 0 are filtered by IndexedDb's RemoteDocumentCache.
  5789. // TODO(#2149): Remove this when Emulator is fixed
  5790. n = qs(e)), new Gn(n, t.transformResults || []);
  5791. }(t, e)))) : [];
  5792. }
  5793. function si(t, e) {
  5794. return {
  5795. documents: [ js(t, e.path) ]
  5796. };
  5797. }
  5798. function ii(t, e) {
  5799. // Dissect the path into parent, collectionId, and optional key filter.
  5800. const n = {
  5801. structuredQuery: {}
  5802. }, s = e.path;
  5803. null !== e.collectionGroup ? (n.parent = js(t, s), n.structuredQuery.from = [ {
  5804. collectionId: e.collectionGroup,
  5805. allDescendants: !0
  5806. } ]) : (n.parent = js(t, s.popLast()), n.structuredQuery.from = [ {
  5807. collectionId: s.lastSegment()
  5808. } ]);
  5809. const i = function(t) {
  5810. if (0 === t.length) return;
  5811. return di(be.create(t, "and" /* CompositeOperator.AND */));
  5812. }(e.filters);
  5813. i && (n.structuredQuery.where = i);
  5814. const r = function(t) {
  5815. if (0 === t.length) return;
  5816. return t.map((t =>
  5817. // visible for testing
  5818. function(t) {
  5819. return {
  5820. field: li(t.field),
  5821. direction: ci(t.dir)
  5822. };
  5823. }(t)));
  5824. }(e.orderBy);
  5825. r && (n.structuredQuery.orderBy = r);
  5826. const o = function(t, e) {
  5827. return t.wt || qt(e) ? e : {
  5828. value: e
  5829. };
  5830. }
  5831. /**
  5832. * Returns a number (or null) from a google.protobuf.Int32Value proto.
  5833. */ (t, e.limit);
  5834. var u;
  5835. return null !== o && (n.structuredQuery.limit = o), e.startAt && (n.structuredQuery.startAt = {
  5836. before: (u = e.startAt).inclusive,
  5837. values: u.position
  5838. }), e.endAt && (n.structuredQuery.endAt = function(t) {
  5839. return {
  5840. before: !t.inclusive,
  5841. values: t.position
  5842. };
  5843. }(e.endAt)), n;
  5844. }
  5845. function ri(t) {
  5846. let e = Ws(t.parent);
  5847. const n = t.structuredQuery, s = n.from ? n.from.length : 0;
  5848. let i = null;
  5849. if (s > 0) {
  5850. M(1 === s);
  5851. const t = n.from[0];
  5852. t.allDescendants ? i = t.collectionId : e = e.child(t.collectionId);
  5853. }
  5854. let r = [];
  5855. n.where && (r = function(t) {
  5856. const e = ui(t);
  5857. if (e instanceof be && Ve(e)) return e.getFilters();
  5858. return [ e ];
  5859. }(n.where));
  5860. let o = [];
  5861. n.orderBy && (o = n.orderBy.map((t => function(t) {
  5862. return new Ue(fi(t.field),
  5863. // visible for testing
  5864. function(t) {
  5865. switch (t) {
  5866. case "ASCENDING":
  5867. return "asc" /* Direction.ASCENDING */;
  5868. case "DESCENDING":
  5869. return "desc" /* Direction.DESCENDING */;
  5870. default:
  5871. return;
  5872. }
  5873. }
  5874. // visible for testing
  5875. (t.direction));
  5876. }
  5877. // visible for testing
  5878. (t))));
  5879. let u = null;
  5880. n.limit && (u = function(t) {
  5881. let e;
  5882. return e = "object" == typeof t ? t.value : t, qt(e) ? null : e;
  5883. }(n.limit));
  5884. let c = null;
  5885. n.startAt && (c = function(t) {
  5886. const e = !!t.before, n = t.values || [];
  5887. return new Ie(n, e);
  5888. }(n.startAt));
  5889. let a = null;
  5890. return n.endAt && (a = function(t) {
  5891. const e = !t.before, n = t.values || [];
  5892. return new Ie(n, e);
  5893. }
  5894. // visible for testing
  5895. (n.endAt)), hn(e, i, o, r, u, "F" /* LimitType.First */ , c, a);
  5896. }
  5897. function oi(t, e) {
  5898. const n = function(t, e) {
  5899. switch (e) {
  5900. case 0 /* TargetPurpose.Listen */ :
  5901. return null;
  5902. case 1 /* TargetPurpose.ExistenceFilterMismatch */ :
  5903. return "existence-filter-mismatch";
  5904. case 2 /* TargetPurpose.LimboResolution */ :
  5905. return "limbo-document";
  5906. default:
  5907. return O();
  5908. }
  5909. }(0, e.purpose);
  5910. return null == n ? null : {
  5911. "goog-listen-tags": n
  5912. };
  5913. }
  5914. function ui(t) {
  5915. return void 0 !== t.unaryFilter ? function(t) {
  5916. switch (t.unaryFilter.op) {
  5917. case "IS_NAN":
  5918. const e = fi(t.unaryFilter.field);
  5919. return Re.create(e, "==" /* Operator.EQUAL */ , {
  5920. doubleValue: NaN
  5921. });
  5922. case "IS_NULL":
  5923. const n = fi(t.unaryFilter.field);
  5924. return Re.create(n, "==" /* Operator.EQUAL */ , {
  5925. nullValue: "NULL_VALUE"
  5926. });
  5927. case "IS_NOT_NAN":
  5928. const s = fi(t.unaryFilter.field);
  5929. return Re.create(s, "!=" /* Operator.NOT_EQUAL */ , {
  5930. doubleValue: NaN
  5931. });
  5932. case "IS_NOT_NULL":
  5933. const i = fi(t.unaryFilter.field);
  5934. return Re.create(i, "!=" /* Operator.NOT_EQUAL */ , {
  5935. nullValue: "NULL_VALUE"
  5936. });
  5937. default:
  5938. return O();
  5939. }
  5940. }(t) : void 0 !== t.fieldFilter ? function(t) {
  5941. return Re.create(fi(t.fieldFilter.field), function(t) {
  5942. switch (t) {
  5943. case "EQUAL":
  5944. return "==" /* Operator.EQUAL */;
  5945. case "NOT_EQUAL":
  5946. return "!=" /* Operator.NOT_EQUAL */;
  5947. case "GREATER_THAN":
  5948. return ">" /* Operator.GREATER_THAN */;
  5949. case "GREATER_THAN_OR_EQUAL":
  5950. return ">=" /* Operator.GREATER_THAN_OR_EQUAL */;
  5951. case "LESS_THAN":
  5952. return "<" /* Operator.LESS_THAN */;
  5953. case "LESS_THAN_OR_EQUAL":
  5954. return "<=" /* Operator.LESS_THAN_OR_EQUAL */;
  5955. case "ARRAY_CONTAINS":
  5956. return "array-contains" /* Operator.ARRAY_CONTAINS */;
  5957. case "IN":
  5958. return "in" /* Operator.IN */;
  5959. case "NOT_IN":
  5960. return "not-in" /* Operator.NOT_IN */;
  5961. case "ARRAY_CONTAINS_ANY":
  5962. return "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */;
  5963. default:
  5964. return O();
  5965. }
  5966. }(t.fieldFilter.op), t.fieldFilter.value);
  5967. }(t) : void 0 !== t.compositeFilter ? function(t) {
  5968. return be.create(t.compositeFilter.filters.map((t => ui(t))), function(t) {
  5969. switch (t) {
  5970. case "AND":
  5971. return "and" /* CompositeOperator.AND */;
  5972. case "OR":
  5973. return "or" /* CompositeOperator.OR */;
  5974. default:
  5975. return O();
  5976. }
  5977. }(t.compositeFilter.op));
  5978. }(t) : O();
  5979. }
  5980. function ci(t) {
  5981. return ks[t];
  5982. }
  5983. function ai(t) {
  5984. return Os[t];
  5985. }
  5986. function hi(t) {
  5987. return Ms[t];
  5988. }
  5989. function li(t) {
  5990. return {
  5991. fieldPath: t.canonicalString()
  5992. };
  5993. }
  5994. function fi(t) {
  5995. return ut.fromServerFormat(t.fieldPath);
  5996. }
  5997. function di(t) {
  5998. return t instanceof Re ? function(t) {
  5999. if ("==" /* Operator.EQUAL */ === t.op) {
  6000. if (fe(t.value)) return {
  6001. unaryFilter: {
  6002. field: li(t.field),
  6003. op: "IS_NAN"
  6004. }
  6005. };
  6006. if (le(t.value)) return {
  6007. unaryFilter: {
  6008. field: li(t.field),
  6009. op: "IS_NULL"
  6010. }
  6011. };
  6012. } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) {
  6013. if (fe(t.value)) return {
  6014. unaryFilter: {
  6015. field: li(t.field),
  6016. op: "IS_NOT_NAN"
  6017. }
  6018. };
  6019. if (le(t.value)) return {
  6020. unaryFilter: {
  6021. field: li(t.field),
  6022. op: "IS_NOT_NULL"
  6023. }
  6024. };
  6025. }
  6026. return {
  6027. fieldFilter: {
  6028. field: li(t.field),
  6029. op: ai(t.op),
  6030. value: t.value
  6031. }
  6032. };
  6033. }(t) : t instanceof be ? function(t) {
  6034. const e = t.getFilters().map((t => di(t)));
  6035. if (1 === e.length) return e[0];
  6036. return {
  6037. compositeFilter: {
  6038. op: hi(t.op),
  6039. filters: e
  6040. }
  6041. };
  6042. }(t) : O();
  6043. }
  6044. function _i(t) {
  6045. const e = [];
  6046. return t.fields.forEach((t => e.push(t.canonicalString()))), {
  6047. fieldPaths: e
  6048. };
  6049. }
  6050. function wi(t) {
  6051. // Resource names have at least 4 components (project ID, database ID)
  6052. return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2);
  6053. }
  6054. /**
  6055. * @license
  6056. * Copyright 2017 Google LLC
  6057. *
  6058. * Licensed under the Apache License, Version 2.0 (the "License");
  6059. * you may not use this file except in compliance with the License.
  6060. * You may obtain a copy of the License at
  6061. *
  6062. * http://www.apache.org/licenses/LICENSE-2.0
  6063. *
  6064. * Unless required by applicable law or agreed to in writing, software
  6065. * distributed under the License is distributed on an "AS IS" BASIS,
  6066. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6067. * See the License for the specific language governing permissions and
  6068. * limitations under the License.
  6069. */
  6070. /**
  6071. * Encodes a resource path into a IndexedDb-compatible string form.
  6072. */
  6073. function mi(t) {
  6074. let e = "";
  6075. for (let n = 0; n < t.length; n++) e.length > 0 && (e = yi(e)), e = gi(t.get(n), e);
  6076. return yi(e);
  6077. }
  6078. /** Encodes a single segment of a resource path into the given result */ function gi(t, e) {
  6079. let n = e;
  6080. const s = t.length;
  6081. for (let e = 0; e < s; e++) {
  6082. const s = t.charAt(e);
  6083. switch (s) {
  6084. case "\0":
  6085. n += "";
  6086. break;
  6087. case "":
  6088. n += "";
  6089. break;
  6090. default:
  6091. n += s;
  6092. }
  6093. }
  6094. return n;
  6095. }
  6096. /** Encodes a path separator into the given result */ function yi(t) {
  6097. return t + "";
  6098. }
  6099. /**
  6100. * Decodes the given IndexedDb-compatible string form of a resource path into
  6101. * a ResourcePath instance. Note that this method is not suitable for use with
  6102. * decoding resource names from the server; those are One Platform format
  6103. * strings.
  6104. */ function pi(t) {
  6105. // Event the empty path must encode as a path of at least length 2. A path
  6106. // with exactly 2 must be the empty path.
  6107. const e = t.length;
  6108. if (M(e >= 2), 2 === e) return M("" === t.charAt(0) && "" === t.charAt(1)), rt.emptyPath();
  6109. // Escape characters cannot exist past the second-to-last position in the
  6110. // source value.
  6111. const n = e - 2, s = [];
  6112. let i = "";
  6113. for (let r = 0; r < e; ) {
  6114. // The last two characters of a valid encoded path must be a separator, so
  6115. // there must be an end to this segment.
  6116. const e = t.indexOf("", r);
  6117. (e < 0 || e > n) && O();
  6118. switch (t.charAt(e + 1)) {
  6119. case "":
  6120. const n = t.substring(r, e);
  6121. let o;
  6122. 0 === i.length ?
  6123. // Avoid copying for the common case of a segment that excludes \0
  6124. // and \001
  6125. o = n : (i += n, o = i, i = ""), s.push(o);
  6126. break;
  6127. case "":
  6128. i += t.substring(r, e), i += "\0";
  6129. break;
  6130. case "":
  6131. // The escape character can be used in the output to encode itself.
  6132. i += t.substring(r, e + 1);
  6133. break;
  6134. default:
  6135. O();
  6136. }
  6137. r = e + 2;
  6138. }
  6139. return new rt(s);
  6140. }
  6141. /**
  6142. * @license
  6143. * Copyright 2022 Google LLC
  6144. *
  6145. * Licensed under the Apache License, Version 2.0 (the "License");
  6146. * you may not use this file except in compliance with the License.
  6147. * You may obtain a copy of the License at
  6148. *
  6149. * http://www.apache.org/licenses/LICENSE-2.0
  6150. *
  6151. * Unless required by applicable law or agreed to in writing, software
  6152. * distributed under the License is distributed on an "AS IS" BASIS,
  6153. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6154. * See the License for the specific language governing permissions and
  6155. * limitations under the License.
  6156. */ const Ii = [ "userId", "batchId" ];
  6157. /**
  6158. * @license
  6159. * Copyright 2022 Google LLC
  6160. *
  6161. * Licensed under the Apache License, Version 2.0 (the "License");
  6162. * you may not use this file except in compliance with the License.
  6163. * You may obtain a copy of the License at
  6164. *
  6165. * http://www.apache.org/licenses/LICENSE-2.0
  6166. *
  6167. * Unless required by applicable law or agreed to in writing, software
  6168. * distributed under the License is distributed on an "AS IS" BASIS,
  6169. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6170. * See the License for the specific language governing permissions and
  6171. * limitations under the License.
  6172. */
  6173. /**
  6174. * Name of the IndexedDb object store.
  6175. *
  6176. * Note that the name 'owner' is chosen to ensure backwards compatibility with
  6177. * older clients that only supported single locked access to the persistence
  6178. * layer.
  6179. */
  6180. /**
  6181. * Creates a [userId, encodedPath] key for use in the DbDocumentMutations
  6182. * index to iterate over all at document mutations for a given path or lower.
  6183. */
  6184. function Ti(t, e) {
  6185. return [ t, mi(e) ];
  6186. }
  6187. /**
  6188. * Creates a full index key of [userId, encodedPath, batchId] for inserting
  6189. * and deleting into the DbDocumentMutations index.
  6190. */ function Ei(t, e, n) {
  6191. return [ t, mi(e), n ];
  6192. }
  6193. /**
  6194. * Because we store all the useful information for this store in the key,
  6195. * there is no useful information to store as the value. The raw (unencoded)
  6196. * path cannot be stored because IndexedDb doesn't store prototype
  6197. * information.
  6198. */ const Ai = {}, Ri = [ "prefixPath", "collectionGroup", "readTime", "documentId" ], bi = [ "prefixPath", "collectionGroup", "documentId" ], Pi = [ "collectionGroup", "readTime", "prefixPath", "documentId" ], vi = [ "canonicalId", "targetId" ], Vi = [ "targetId", "path" ], Si = [ "path", "targetId" ], Di = [ "collectionId", "parent" ], Ci = [ "indexId", "uid" ], xi = [ "uid", "sequenceNumber" ], Ni = [ "indexId", "uid", "arrayValue", "directionalValue", "orderedDocumentKey", "documentKey" ], ki = [ "indexId", "uid", "orderedDocumentKey" ], Oi = [ "userId", "collectionPath", "documentId" ], Mi = [ "userId", "collectionPath", "largestBatchId" ], Fi = [ "userId", "collectionGroup", "largestBatchId" ], $i = [ ...[ ...[ ...[ ...[ "mutationQueues", "mutations", "documentMutations", "remoteDocuments", "targets", "owner", "targetGlobal", "targetDocuments" ], "clientMetadata" ], "remoteDocumentGlobal" ], "collectionParents" ], "bundles", "namedQueries" ], Bi = [ ...$i, "documentOverlays" ], Li = [ "mutationQueues", "mutations", "documentMutations", "remoteDocumentsV14", "targets", "owner", "targetGlobal", "targetDocuments", "clientMetadata", "remoteDocumentGlobal", "collectionParents", "bundles", "namedQueries", "documentOverlays" ], qi = Li, Ui = [ ...qi, "indexConfiguration", "indexState", "indexEntries" ];
  6199. /**
  6200. * @license
  6201. * Copyright 2020 Google LLC
  6202. *
  6203. * Licensed under the Apache License, Version 2.0 (the "License");
  6204. * you may not use this file except in compliance with the License.
  6205. * You may obtain a copy of the License at
  6206. *
  6207. * http://www.apache.org/licenses/LICENSE-2.0
  6208. *
  6209. * Unless required by applicable law or agreed to in writing, software
  6210. * distributed under the License is distributed on an "AS IS" BASIS,
  6211. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6212. * See the License for the specific language governing permissions and
  6213. * limitations under the License.
  6214. */
  6215. class Ki extends Tt {
  6216. constructor(t, e) {
  6217. super(), this.se = t, this.currentSequenceNumber = e;
  6218. }
  6219. }
  6220. function Gi(t, e) {
  6221. const n = $(t);
  6222. return bt.M(n.se, e);
  6223. }
  6224. /**
  6225. * @license
  6226. * Copyright 2017 Google LLC
  6227. *
  6228. * Licensed under the Apache License, Version 2.0 (the "License");
  6229. * you may not use this file except in compliance with the License.
  6230. * You may obtain a copy of the License at
  6231. *
  6232. * http://www.apache.org/licenses/LICENSE-2.0
  6233. *
  6234. * Unless required by applicable law or agreed to in writing, software
  6235. * distributed under the License is distributed on an "AS IS" BASIS,
  6236. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6237. * See the License for the specific language governing permissions and
  6238. * limitations under the License.
  6239. */
  6240. /**
  6241. * A batch of mutations that will be sent as one unit to the backend.
  6242. */ class Qi {
  6243. /**
  6244. * @param batchId - The unique ID of this mutation batch.
  6245. * @param localWriteTime - The original write time of this mutation.
  6246. * @param baseMutations - Mutations that are used to populate the base
  6247. * values when this mutation is applied locally. This can be used to locally
  6248. * overwrite values that are persisted in the remote document cache. Base
  6249. * mutations are never sent to the backend.
  6250. * @param mutations - The user-provided mutations in this mutation batch.
  6251. * User-provided mutations are applied both locally and remotely on the
  6252. * backend.
  6253. */
  6254. constructor(t, e, n, s) {
  6255. this.batchId = t, this.localWriteTime = e, this.baseMutations = n, this.mutations = s;
  6256. }
  6257. /**
  6258. * Applies all the mutations in this MutationBatch to the specified document
  6259. * to compute the state of the remote document
  6260. *
  6261. * @param document - The document to apply mutations to.
  6262. * @param batchResult - The result of applying the MutationBatch to the
  6263. * backend.
  6264. */ applyToRemoteDocument(t, e) {
  6265. const n = e.mutationResults;
  6266. for (let e = 0; e < this.mutations.length; e++) {
  6267. const s = this.mutations[e];
  6268. if (s.key.isEqual(t.key)) {
  6269. Hn(s, t, n[e]);
  6270. }
  6271. }
  6272. }
  6273. /**
  6274. * Computes the local view of a document given all the mutations in this
  6275. * batch.
  6276. *
  6277. * @param document - The document to apply mutations to.
  6278. * @param mutatedFields - Fields that have been updated before applying this mutation batch.
  6279. * @returns A `FieldMask` representing all the fields that are mutated.
  6280. */ applyToLocalView(t, e) {
  6281. // First, apply the base state. This allows us to apply non-idempotent
  6282. // transform against a consistent set of values.
  6283. for (const n of this.baseMutations) n.key.isEqual(t.key) && (e = Jn(n, t, e, this.localWriteTime));
  6284. // Second, apply all user-provided mutations.
  6285. for (const n of this.mutations) n.key.isEqual(t.key) && (e = Jn(n, t, e, this.localWriteTime));
  6286. return e;
  6287. }
  6288. /**
  6289. * Computes the local view for all provided documents given the mutations in
  6290. * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to
  6291. * replace all the mutation applications.
  6292. */ applyToLocalDocumentSet(t, e) {
  6293. // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations
  6294. // directly (as done in `applyToLocalView()`), we can reduce the complexity
  6295. // to O(n).
  6296. const n = ys();
  6297. return this.mutations.forEach((s => {
  6298. const i = t.get(s.key), r = i.overlayedDocument;
  6299. // TODO(mutabledocuments): This method should take a MutableDocumentMap
  6300. // and we should remove this cast.
  6301. let o = this.applyToLocalView(r, i.mutatedFields);
  6302. // Set mutatedFields to null if the document is only from local mutations.
  6303. // This creates a Set or Delete mutation, instead of trying to create a
  6304. // patch mutation as the overlay.
  6305. o = e.has(s.key) ? null : o;
  6306. const u = zn(r, o);
  6307. null !== u && n.set(s.key, u), r.isValidDocument() || r.convertToNoDocument(st.min());
  6308. })), n;
  6309. }
  6310. keys() {
  6311. return this.mutations.reduce(((t, e) => t.add(e.key)), Es());
  6312. }
  6313. isEqual(t) {
  6314. return this.batchId === t.batchId && tt(this.mutations, t.mutations, ((t, e) => Xn(t, e))) && tt(this.baseMutations, t.baseMutations, ((t, e) => Xn(t, e)));
  6315. }
  6316. }
  6317. /** The result of applying a mutation batch to the backend. */ class ji {
  6318. constructor(t, e, n,
  6319. /**
  6320. * A pre-computed mapping from each mutated document to the resulting
  6321. * version.
  6322. */
  6323. s) {
  6324. this.batch = t, this.commitVersion = e, this.mutationResults = n, this.docVersions = s;
  6325. }
  6326. /**
  6327. * Creates a new MutationBatchResult for the given batch and results. There
  6328. * must be one result for each mutation in the batch. This static factory
  6329. * caches a document=&gt;version mapping (docVersions).
  6330. */ static from(t, e, n) {
  6331. M(t.mutations.length === n.length);
  6332. let s = Is;
  6333. const i = t.mutations;
  6334. for (let t = 0; t < i.length; t++) s = s.insert(i[t].key, n[t].version);
  6335. return new ji(t, e, n, s);
  6336. }
  6337. }
  6338. /**
  6339. * @license
  6340. * Copyright 2022 Google LLC
  6341. *
  6342. * Licensed under the Apache License, Version 2.0 (the "License");
  6343. * you may not use this file except in compliance with the License.
  6344. * You may obtain a copy of the License at
  6345. *
  6346. * http://www.apache.org/licenses/LICENSE-2.0
  6347. *
  6348. * Unless required by applicable law or agreed to in writing, software
  6349. * distributed under the License is distributed on an "AS IS" BASIS,
  6350. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6351. * See the License for the specific language governing permissions and
  6352. * limitations under the License.
  6353. */
  6354. /**
  6355. * Representation of an overlay computed by Firestore.
  6356. *
  6357. * Holds information about a mutation and the largest batch id in Firestore when
  6358. * the mutation was created.
  6359. */ class Wi {
  6360. constructor(t, e) {
  6361. this.largestBatchId = t, this.mutation = e;
  6362. }
  6363. getKey() {
  6364. return this.mutation.key;
  6365. }
  6366. isEqual(t) {
  6367. return null !== t && this.mutation === t.mutation;
  6368. }
  6369. toString() {
  6370. return `Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`;
  6371. }
  6372. }
  6373. /**
  6374. * @license
  6375. * Copyright 2017 Google LLC
  6376. *
  6377. * Licensed under the Apache License, Version 2.0 (the "License");
  6378. * you may not use this file except in compliance with the License.
  6379. * You may obtain a copy of the License at
  6380. *
  6381. * http://www.apache.org/licenses/LICENSE-2.0
  6382. *
  6383. * Unless required by applicable law or agreed to in writing, software
  6384. * distributed under the License is distributed on an "AS IS" BASIS,
  6385. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6386. * See the License for the specific language governing permissions and
  6387. * limitations under the License.
  6388. */
  6389. /**
  6390. * An immutable set of metadata that the local store tracks for each target.
  6391. */ class zi {
  6392. constructor(
  6393. /** The target being listened to. */
  6394. t,
  6395. /**
  6396. * The target ID to which the target corresponds; Assigned by the
  6397. * LocalStore for user listens and by the SyncEngine for limbo watches.
  6398. */
  6399. e,
  6400. /** The purpose of the target. */
  6401. n,
  6402. /**
  6403. * The sequence number of the last transaction during which this target data
  6404. * was modified.
  6405. */
  6406. s,
  6407. /** The latest snapshot version seen for this target. */
  6408. i = st.min()
  6409. /**
  6410. * The maximum snapshot version at which the associated view
  6411. * contained no limbo documents.
  6412. */ , r = st.min()
  6413. /**
  6414. * An opaque, server-assigned token that allows watching a target to be
  6415. * resumed after disconnecting without retransmitting all the data that
  6416. * matches the target. The resume token essentially identifies a point in
  6417. * time from which the server should resume sending results.
  6418. */ , o = Qt.EMPTY_BYTE_STRING) {
  6419. this.target = t, this.targetId = e, this.purpose = n, this.sequenceNumber = s, this.snapshotVersion = i,
  6420. this.lastLimboFreeSnapshotVersion = r, this.resumeToken = o;
  6421. }
  6422. /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(t) {
  6423. return new zi(this.target, this.targetId, this.purpose, t, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken);
  6424. }
  6425. /**
  6426. * Creates a new target data instance with an updated resume token and
  6427. * snapshot version.
  6428. */ withResumeToken(t, e) {
  6429. return new zi(this.target, this.targetId, this.purpose, this.sequenceNumber, e, this.lastLimboFreeSnapshotVersion, t);
  6430. }
  6431. /**
  6432. * Creates a new target data instance with an updated last limbo free
  6433. * snapshot version number.
  6434. */ withLastLimboFreeSnapshotVersion(t) {
  6435. return new zi(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, t, this.resumeToken);
  6436. }
  6437. }
  6438. /**
  6439. * @license
  6440. * Copyright 2017 Google LLC
  6441. *
  6442. * Licensed under the Apache License, Version 2.0 (the "License");
  6443. * you may not use this file except in compliance with the License.
  6444. * You may obtain a copy of the License at
  6445. *
  6446. * http://www.apache.org/licenses/LICENSE-2.0
  6447. *
  6448. * Unless required by applicable law or agreed to in writing, software
  6449. * distributed under the License is distributed on an "AS IS" BASIS,
  6450. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6451. * See the License for the specific language governing permissions and
  6452. * limitations under the License.
  6453. */
  6454. /** Serializer for values stored in the LocalStore. */ class Hi {
  6455. constructor(t) {
  6456. this.ie = t;
  6457. }
  6458. }
  6459. /** Decodes a remote document from storage locally to a Document. */ function Ji(t, e) {
  6460. let n;
  6461. if (e.document) n = Ys(t.ie, e.document, !!e.hasCommittedMutations); else if (e.noDocument) {
  6462. const t = ct.fromSegments(e.noDocument.path), s = tr(e.noDocument.readTime);
  6463. n = Ze.newNoDocument(t, s), e.hasCommittedMutations && n.setHasCommittedMutations();
  6464. } else {
  6465. if (!e.unknownDocument) return O();
  6466. {
  6467. const t = ct.fromSegments(e.unknownDocument.path), s = tr(e.unknownDocument.version);
  6468. n = Ze.newUnknownDocument(t, s);
  6469. }
  6470. }
  6471. return e.readTime && n.setReadTime(function(t) {
  6472. const e = new nt(t[0], t[1]);
  6473. return st.fromTimestamp(e);
  6474. }(e.readTime)), n;
  6475. }
  6476. /** Encodes a document for storage locally. */ function Yi(t, e) {
  6477. const n = e.key, s = {
  6478. prefixPath: n.getCollectionPath().popLast().toArray(),
  6479. collectionGroup: n.collectionGroup,
  6480. documentId: n.path.lastSegment(),
  6481. readTime: Xi(e.readTime),
  6482. hasCommittedMutations: e.hasCommittedMutations
  6483. };
  6484. if (e.isFoundDocument()) s.document = function(t, e) {
  6485. return {
  6486. name: Gs(t, e.key),
  6487. fields: e.data.value.mapValue.fields,
  6488. updateTime: $s(t, e.version.toTimestamp()),
  6489. createTime: $s(t, e.createTime.toTimestamp())
  6490. };
  6491. }(t.ie, e); else if (e.isNoDocument()) s.noDocument = {
  6492. path: n.path.toArray(),
  6493. readTime: Zi(e.version)
  6494. }; else {
  6495. if (!e.isUnknownDocument()) return O();
  6496. s.unknownDocument = {
  6497. path: n.path.toArray(),
  6498. version: Zi(e.version)
  6499. };
  6500. }
  6501. return s;
  6502. }
  6503. function Xi(t) {
  6504. const e = t.toTimestamp();
  6505. return [ e.seconds, e.nanoseconds ];
  6506. }
  6507. function Zi(t) {
  6508. const e = t.toTimestamp();
  6509. return {
  6510. seconds: e.seconds,
  6511. nanoseconds: e.nanoseconds
  6512. };
  6513. }
  6514. function tr(t) {
  6515. const e = new nt(t.seconds, t.nanoseconds);
  6516. return st.fromTimestamp(e);
  6517. }
  6518. /** Encodes a batch of mutations into a DbMutationBatch for local storage. */
  6519. /** Decodes a DbMutationBatch into a MutationBatch */
  6520. function er(t, e) {
  6521. const n = (e.baseMutations || []).map((e => ei(t.ie, e)));
  6522. // Squash old transform mutations into existing patch or set mutations.
  6523. // The replacement of representing `transforms` with `update_transforms`
  6524. // on the SDK means that old `transform` mutations stored in IndexedDB need
  6525. // to be updated to `update_transforms`.
  6526. // TODO(b/174608374): Remove this code once we perform a schema migration.
  6527. for (let t = 0; t < e.mutations.length - 1; ++t) {
  6528. const n = e.mutations[t];
  6529. if (t + 1 < e.mutations.length && void 0 !== e.mutations[t + 1].transform) {
  6530. const s = e.mutations[t + 1];
  6531. n.updateTransforms = s.transform.fieldTransforms, e.mutations.splice(t + 1, 1),
  6532. ++t;
  6533. }
  6534. }
  6535. const s = e.mutations.map((e => ei(t.ie, e))), i = nt.fromMillis(e.localWriteTimeMs);
  6536. return new Qi(e.batchId, i, n, s);
  6537. }
  6538. /** Decodes a DbTarget into TargetData */ function nr(t) {
  6539. const e = tr(t.readTime), n = void 0 !== t.lastLimboFreeSnapshotVersion ? tr(t.lastLimboFreeSnapshotVersion) : st.min();
  6540. let s;
  6541. var i;
  6542. return void 0 !== t.query.documents ? (M(1 === (i = t.query).documents.length),
  6543. s = gn(ln(Ws(i.documents[0])))) : s = function(t) {
  6544. return gn(ri(t));
  6545. }(t.query), new zi(s, t.targetId, 0 /* TargetPurpose.Listen */ , t.lastListenSequenceNumber, e, n, Qt.fromBase64String(t.resumeToken));
  6546. }
  6547. /** Encodes TargetData into a DbTarget for storage locally. */ function sr(t, e) {
  6548. const n = Zi(e.snapshotVersion), s = Zi(e.lastLimboFreeSnapshotVersion);
  6549. let i;
  6550. i = rn(e.target) ? si(t.ie, e.target) : ii(t.ie, e.target);
  6551. // We can't store the resumeToken as a ByteString in IndexedDb, so we
  6552. // convert it to a base64 string for storage.
  6553. const r = e.resumeToken.toBase64();
  6554. // lastListenSequenceNumber is always 0 until we do real GC.
  6555. return {
  6556. targetId: e.targetId,
  6557. canonicalId: nn(e.target),
  6558. readTime: n,
  6559. resumeToken: r,
  6560. lastListenSequenceNumber: e.sequenceNumber,
  6561. lastLimboFreeSnapshotVersion: s,
  6562. query: i
  6563. };
  6564. }
  6565. /**
  6566. * A helper function for figuring out what kind of query has been stored.
  6567. */
  6568. /**
  6569. * Encodes a `BundledQuery` from bundle proto to a Query object.
  6570. *
  6571. * This reconstructs the original query used to build the bundle being loaded,
  6572. * including features exists only in SDKs (for example: limit-to-last).
  6573. */
  6574. function ir(t) {
  6575. const e = ri({
  6576. parent: t.parent,
  6577. structuredQuery: t.structuredQuery
  6578. });
  6579. return "LAST" === t.limitType ? pn(e, e.limit, "L" /* LimitType.Last */) : e;
  6580. }
  6581. /** Encodes a NamedQuery proto object to a NamedQuery model object. */
  6582. /** Encodes a DbDocumentOverlay object to an Overlay model object. */
  6583. function rr(t, e) {
  6584. return new Wi(e.largestBatchId, ei(t.ie, e.overlayMutation));
  6585. }
  6586. /** Decodes an Overlay model object into a DbDocumentOverlay object. */
  6587. /**
  6588. * Returns the DbDocumentOverlayKey corresponding to the given user and
  6589. * document key.
  6590. */
  6591. function or(t, e) {
  6592. const n = e.path.lastSegment();
  6593. return [ t, mi(e.path.popLast()), n ];
  6594. }
  6595. function ur(t, e, n, s) {
  6596. return {
  6597. indexId: t,
  6598. uid: e.uid || "",
  6599. sequenceNumber: n,
  6600. readTime: Zi(s.readTime),
  6601. documentKey: mi(s.documentKey.path),
  6602. largestBatchId: s.largestBatchId
  6603. };
  6604. }
  6605. /**
  6606. * @license
  6607. * Copyright 2020 Google LLC
  6608. *
  6609. * Licensed under the Apache License, Version 2.0 (the "License");
  6610. * you may not use this file except in compliance with the License.
  6611. * You may obtain a copy of the License at
  6612. *
  6613. * http://www.apache.org/licenses/LICENSE-2.0
  6614. *
  6615. * Unless required by applicable law or agreed to in writing, software
  6616. * distributed under the License is distributed on an "AS IS" BASIS,
  6617. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6618. * See the License for the specific language governing permissions and
  6619. * limitations under the License.
  6620. */ class cr {
  6621. getBundleMetadata(t, e) {
  6622. return ar(t).get(e).next((t => {
  6623. if (t) return {
  6624. id: (e = t).bundleId,
  6625. createTime: tr(e.createTime),
  6626. version: e.version
  6627. };
  6628. /** Encodes a DbBundle to a BundleMetadata object. */
  6629. var e;
  6630. /** Encodes a BundleMetadata to a DbBundle. */ }));
  6631. }
  6632. saveBundleMetadata(t, e) {
  6633. return ar(t).put({
  6634. bundleId: (n = e).id,
  6635. createTime: Zi(qs(n.createTime)),
  6636. version: n.version
  6637. });
  6638. var n;
  6639. /** Encodes a DbNamedQuery to a NamedQuery. */ }
  6640. getNamedQuery(t, e) {
  6641. return hr(t).get(e).next((t => {
  6642. if (t) return {
  6643. name: (e = t).name,
  6644. query: ir(e.bundledQuery),
  6645. readTime: tr(e.readTime)
  6646. };
  6647. var e;
  6648. /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ }));
  6649. }
  6650. saveNamedQuery(t, e) {
  6651. return hr(t).put(function(t) {
  6652. return {
  6653. name: t.name,
  6654. readTime: Zi(qs(t.readTime)),
  6655. bundledQuery: t.bundledQuery
  6656. };
  6657. }(e));
  6658. }
  6659. }
  6660. /**
  6661. * Helper to get a typed SimpleDbStore for the bundles object store.
  6662. */ function ar(t) {
  6663. return Gi(t, "bundles");
  6664. }
  6665. /**
  6666. * Helper to get a typed SimpleDbStore for the namedQueries object store.
  6667. */ function hr(t) {
  6668. return Gi(t, "namedQueries");
  6669. }
  6670. /**
  6671. * @license
  6672. * Copyright 2022 Google LLC
  6673. *
  6674. * Licensed under the Apache License, Version 2.0 (the "License");
  6675. * you may not use this file except in compliance with the License.
  6676. * You may obtain a copy of the License at
  6677. *
  6678. * http://www.apache.org/licenses/LICENSE-2.0
  6679. *
  6680. * Unless required by applicable law or agreed to in writing, software
  6681. * distributed under the License is distributed on an "AS IS" BASIS,
  6682. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6683. * See the License for the specific language governing permissions and
  6684. * limitations under the License.
  6685. */
  6686. /**
  6687. * Implementation of DocumentOverlayCache using IndexedDb.
  6688. */ class lr {
  6689. /**
  6690. * @param serializer - The document serializer.
  6691. * @param userId - The userId for which we are accessing overlays.
  6692. */
  6693. constructor(t, e) {
  6694. this.yt = t, this.userId = e;
  6695. }
  6696. static re(t, e) {
  6697. const n = e.uid || "";
  6698. return new lr(t, n);
  6699. }
  6700. getOverlay(t, e) {
  6701. return fr(t).get(or(this.userId, e)).next((t => t ? rr(this.yt, t) : null));
  6702. }
  6703. getOverlays(t, e) {
  6704. const n = gs();
  6705. return At.forEach(e, (e => this.getOverlay(t, e).next((t => {
  6706. null !== t && n.set(e, t);
  6707. })))).next((() => n));
  6708. }
  6709. saveOverlays(t, e, n) {
  6710. const s = [];
  6711. return n.forEach(((n, i) => {
  6712. const r = new Wi(e, i);
  6713. s.push(this.oe(t, r));
  6714. })), At.waitFor(s);
  6715. }
  6716. removeOverlaysForBatchId(t, e, n) {
  6717. const s = new Set;
  6718. // Get the set of unique collection paths.
  6719. e.forEach((t => s.add(mi(t.getCollectionPath()))));
  6720. const i = [];
  6721. return s.forEach((e => {
  6722. const s = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, n + 1 ],
  6723. /*lowerOpen=*/ !1,
  6724. /*upperOpen=*/ !0);
  6725. i.push(fr(t).Y("collectionPathOverlayIndex", s));
  6726. })), At.waitFor(i);
  6727. }
  6728. getOverlaysForCollection(t, e, n) {
  6729. const s = gs(), i = mi(e), r = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ],
  6730. /*lowerOpen=*/ !0);
  6731. return fr(t).W("collectionPathOverlayIndex", r).next((t => {
  6732. for (const e of t) {
  6733. const t = rr(this.yt, e);
  6734. s.set(t.getKey(), t);
  6735. }
  6736. return s;
  6737. }));
  6738. }
  6739. getOverlaysForCollectionGroup(t, e, n, s) {
  6740. const i = gs();
  6741. let r;
  6742. // We want batch IDs larger than `sinceBatchId`, and so the lower bound
  6743. // is not inclusive.
  6744. const o = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, Number.POSITIVE_INFINITY ],
  6745. /*lowerOpen=*/ !0);
  6746. return fr(t).Z({
  6747. index: "collectionGroupOverlayIndex",
  6748. range: o
  6749. }, ((t, e, n) => {
  6750. // We do not want to return partial batch overlays, even if the size
  6751. // of the result set exceeds the given `count` argument. Therefore, we
  6752. // continue to aggregate results even after the result size exceeds
  6753. // `count` if there are more overlays from the `currentBatchId`.
  6754. const o = rr(this.yt, e);
  6755. i.size() < s || o.largestBatchId === r ? (i.set(o.getKey(), o), r = o.largestBatchId) : n.done();
  6756. })).next((() => i));
  6757. }
  6758. oe(t, e) {
  6759. return fr(t).put(function(t, e, n) {
  6760. const [s, i, r] = or(e, n.mutation.key);
  6761. return {
  6762. userId: e,
  6763. collectionPath: i,
  6764. documentId: r,
  6765. collectionGroup: n.mutation.key.getCollectionGroup(),
  6766. largestBatchId: n.largestBatchId,
  6767. overlayMutation: ti(t.ie, n.mutation)
  6768. };
  6769. }(this.yt, this.userId, e));
  6770. }
  6771. }
  6772. /**
  6773. * Helper to get a typed SimpleDbStore for the document overlay object store.
  6774. */ function fr(t) {
  6775. return Gi(t, "documentOverlays");
  6776. }
  6777. /**
  6778. * @license
  6779. * Copyright 2021 Google LLC
  6780. *
  6781. * Licensed under the Apache License, Version 2.0 (the "License");
  6782. * you may not use this file except in compliance with the License.
  6783. * You may obtain a copy of the License at
  6784. *
  6785. * http://www.apache.org/licenses/LICENSE-2.0
  6786. *
  6787. * Unless required by applicable law or agreed to in writing, software
  6788. * distributed under the License is distributed on an "AS IS" BASIS,
  6789. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6790. * See the License for the specific language governing permissions and
  6791. * limitations under the License.
  6792. */
  6793. // Note: This code is copied from the backend. Code that is not used by
  6794. // Firestore was removed.
  6795. /** Firestore index value writer. */
  6796. class dr {
  6797. constructor() {}
  6798. // The write methods below short-circuit writing terminators for values
  6799. // containing a (terminating) truncated value.
  6800. // As an example, consider the resulting encoding for:
  6801. // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM)
  6802. // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC)
  6803. // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC)
  6804. /** Writes an index value. */
  6805. ue(t, e) {
  6806. this.ce(t, e),
  6807. // Write separator to split index values
  6808. // (see go/firestore-storage-format#encodings).
  6809. e.ae();
  6810. }
  6811. ce(t, e) {
  6812. if ("nullValue" in t) this.he(e, 5); else if ("booleanValue" in t) this.he(e, 10),
  6813. e.le(t.booleanValue ? 1 : 0); else if ("integerValue" in t) this.he(e, 15), e.le(zt(t.integerValue)); else if ("doubleValue" in t) {
  6814. const n = zt(t.doubleValue);
  6815. isNaN(n) ? this.he(e, 13) : (this.he(e, 15), Ut(n) ?
  6816. // -0.0, 0 and 0.0 are all considered the same
  6817. e.le(0) : e.le(n));
  6818. } else if ("timestampValue" in t) {
  6819. const n = t.timestampValue;
  6820. this.he(e, 20), "string" == typeof n ? e.fe(n) : (e.fe(`${n.seconds || ""}`), e.le(n.nanos || 0));
  6821. } else if ("stringValue" in t) this.de(t.stringValue, e), this._e(e); else if ("bytesValue" in t) this.he(e, 30),
  6822. e.we(Ht(t.bytesValue)), this._e(e); else if ("referenceValue" in t) this.me(t.referenceValue, e); else if ("geoPointValue" in t) {
  6823. const n = t.geoPointValue;
  6824. this.he(e, 45), e.le(n.latitude || 0), e.le(n.longitude || 0);
  6825. } else "mapValue" in t ? we(t) ? this.he(e, Number.MAX_SAFE_INTEGER) : (this.ge(t.mapValue, e),
  6826. this._e(e)) : "arrayValue" in t ? (this.ye(t.arrayValue, e), this._e(e)) : O();
  6827. }
  6828. de(t, e) {
  6829. this.he(e, 25), this.pe(t, e);
  6830. }
  6831. pe(t, e) {
  6832. e.fe(t);
  6833. }
  6834. ge(t, e) {
  6835. const n = t.fields || {};
  6836. this.he(e, 55);
  6837. for (const t of Object.keys(n)) this.de(t, e), this.ce(n[t], e);
  6838. }
  6839. ye(t, e) {
  6840. const n = t.values || [];
  6841. this.he(e, 50);
  6842. for (const t of n) this.ce(t, e);
  6843. }
  6844. me(t, e) {
  6845. this.he(e, 37);
  6846. ct.fromName(t).path.forEach((t => {
  6847. this.he(e, 60), this.pe(t, e);
  6848. }));
  6849. }
  6850. he(t, e) {
  6851. t.le(e);
  6852. }
  6853. _e(t) {
  6854. // While the SDK does not implement truncation, the truncation marker is
  6855. // used to terminate all variable length values (which are strings, bytes,
  6856. // references, arrays and maps).
  6857. t.le(2);
  6858. }
  6859. }
  6860. dr.Ie = new dr;
  6861. /**
  6862. * Counts the number of zeros in a byte.
  6863. *
  6864. * Visible for testing.
  6865. */
  6866. function _r(t) {
  6867. if (0 === t) return 8;
  6868. let e = 0;
  6869. return t >> 4 == 0 && (
  6870. // Test if the first four bits are zero.
  6871. e += 4, t <<= 4), t >> 6 == 0 && (
  6872. // Test if the first two (or next two) bits are zero.
  6873. e += 2, t <<= 2), t >> 7 == 0 && (
  6874. // Test if the remaining bit is zero.
  6875. e += 1), e;
  6876. }
  6877. /** Counts the number of leading zeros in the given byte array. */
  6878. /**
  6879. * Returns the number of bytes required to store "value". Leading zero bytes
  6880. * are skipped.
  6881. */
  6882. function wr(t) {
  6883. // This is just the number of bytes for the unsigned representation of the number.
  6884. const e = 64 - function(t) {
  6885. let e = 0;
  6886. for (let n = 0; n < 8; ++n) {
  6887. const s = _r(255 & t[n]);
  6888. if (e += s, 8 !== s) break;
  6889. }
  6890. return e;
  6891. }(t);
  6892. return Math.ceil(e / 8);
  6893. }
  6894. /**
  6895. * OrderedCodeWriter is a minimal-allocation implementation of the writing
  6896. * behavior defined by the backend.
  6897. *
  6898. * The code is ported from its Java counterpart.
  6899. */ class mr {
  6900. constructor() {
  6901. this.buffer = new Uint8Array(1024), this.position = 0;
  6902. }
  6903. Te(t) {
  6904. const e = t[Symbol.iterator]();
  6905. let n = e.next();
  6906. for (;!n.done; ) this.Ee(n.value), n = e.next();
  6907. this.Ae();
  6908. }
  6909. Re(t) {
  6910. const e = t[Symbol.iterator]();
  6911. let n = e.next();
  6912. for (;!n.done; ) this.be(n.value), n = e.next();
  6913. this.Pe();
  6914. }
  6915. /** Writes utf8 bytes into this byte sequence, ascending. */ ve(t) {
  6916. for (const e of t) {
  6917. const t = e.charCodeAt(0);
  6918. if (t < 128) this.Ee(t); else if (t < 2048) this.Ee(960 | t >>> 6), this.Ee(128 | 63 & t); else if (e < "\ud800" || "\udbff" < e) this.Ee(480 | t >>> 12),
  6919. this.Ee(128 | 63 & t >>> 6), this.Ee(128 | 63 & t); else {
  6920. const t = e.codePointAt(0);
  6921. this.Ee(240 | t >>> 18), this.Ee(128 | 63 & t >>> 12), this.Ee(128 | 63 & t >>> 6),
  6922. this.Ee(128 | 63 & t);
  6923. }
  6924. }
  6925. this.Ae();
  6926. }
  6927. /** Writes utf8 bytes into this byte sequence, descending */ Ve(t) {
  6928. for (const e of t) {
  6929. const t = e.charCodeAt(0);
  6930. if (t < 128) this.be(t); else if (t < 2048) this.be(960 | t >>> 6), this.be(128 | 63 & t); else if (e < "\ud800" || "\udbff" < e) this.be(480 | t >>> 12),
  6931. this.be(128 | 63 & t >>> 6), this.be(128 | 63 & t); else {
  6932. const t = e.codePointAt(0);
  6933. this.be(240 | t >>> 18), this.be(128 | 63 & t >>> 12), this.be(128 | 63 & t >>> 6),
  6934. this.be(128 | 63 & t);
  6935. }
  6936. }
  6937. this.Pe();
  6938. }
  6939. Se(t) {
  6940. // Values are encoded with a single byte length prefix, followed by the
  6941. // actual value in big-endian format with leading 0 bytes dropped.
  6942. const e = this.De(t), n = wr(e);
  6943. this.Ce(1 + n), this.buffer[this.position++] = 255 & n;
  6944. // Write the length
  6945. for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = 255 & e[t];
  6946. }
  6947. xe(t) {
  6948. // Values are encoded with a single byte length prefix, followed by the
  6949. // inverted value in big-endian format with leading 0 bytes dropped.
  6950. const e = this.De(t), n = wr(e);
  6951. this.Ce(1 + n), this.buffer[this.position++] = ~(255 & n);
  6952. // Write the length
  6953. for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = ~(255 & e[t]);
  6954. }
  6955. /**
  6956. * Writes the "infinity" byte sequence that sorts after all other byte
  6957. * sequences written in ascending order.
  6958. */ Ne() {
  6959. this.ke(255), this.ke(255);
  6960. }
  6961. /**
  6962. * Writes the "infinity" byte sequence that sorts before all other byte
  6963. * sequences written in descending order.
  6964. */ Oe() {
  6965. this.Me(255), this.Me(255);
  6966. }
  6967. /**
  6968. * Resets the buffer such that it is the same as when it was newly
  6969. * constructed.
  6970. */ reset() {
  6971. this.position = 0;
  6972. }
  6973. seed(t) {
  6974. this.Ce(t.length), this.buffer.set(t, this.position), this.position += t.length;
  6975. }
  6976. /** Makes a copy of the encoded bytes in this buffer. */ Fe() {
  6977. return this.buffer.slice(0, this.position);
  6978. }
  6979. /**
  6980. * Encodes `val` into an encoding so that the order matches the IEEE 754
  6981. * floating-point comparison results with the following exceptions:
  6982. * -0.0 < 0.0
  6983. * all non-NaN < NaN
  6984. * NaN = NaN
  6985. */ De(t) {
  6986. const e =
  6987. /** Converts a JavaScript number to a byte array (using big endian encoding). */
  6988. function(t) {
  6989. const e = new DataView(new ArrayBuffer(8));
  6990. return e.setFloat64(0, t, /* littleEndian= */ !1), new Uint8Array(e.buffer);
  6991. }(t), n = 0 != (128 & e[0]);
  6992. // Check if the first bit is set. We use a bit mask since value[0] is
  6993. // encoded as a number from 0 to 255.
  6994. // Revert the two complement to get natural ordering
  6995. e[0] ^= n ? 255 : 128;
  6996. for (let t = 1; t < e.length; ++t) e[t] ^= n ? 255 : 0;
  6997. return e;
  6998. }
  6999. /** Writes a single byte ascending to the buffer. */ Ee(t) {
  7000. const e = 255 & t;
  7001. 0 === e ? (this.ke(0), this.ke(255)) : 255 === e ? (this.ke(255), this.ke(0)) : this.ke(e);
  7002. }
  7003. /** Writes a single byte descending to the buffer. */ be(t) {
  7004. const e = 255 & t;
  7005. 0 === e ? (this.Me(0), this.Me(255)) : 255 === e ? (this.Me(255), this.Me(0)) : this.Me(t);
  7006. }
  7007. Ae() {
  7008. this.ke(0), this.ke(1);
  7009. }
  7010. Pe() {
  7011. this.Me(0), this.Me(1);
  7012. }
  7013. ke(t) {
  7014. this.Ce(1), this.buffer[this.position++] = t;
  7015. }
  7016. Me(t) {
  7017. this.Ce(1), this.buffer[this.position++] = ~t;
  7018. }
  7019. Ce(t) {
  7020. const e = t + this.position;
  7021. if (e <= this.buffer.length) return;
  7022. // Try doubling.
  7023. let n = 2 * this.buffer.length;
  7024. // Still not big enough? Just allocate the right size.
  7025. n < e && (n = e);
  7026. // Create the new buffer.
  7027. const s = new Uint8Array(n);
  7028. s.set(this.buffer), // copy old data
  7029. this.buffer = s;
  7030. }
  7031. }
  7032. class gr {
  7033. constructor(t) {
  7034. this.$e = t;
  7035. }
  7036. we(t) {
  7037. this.$e.Te(t);
  7038. }
  7039. fe(t) {
  7040. this.$e.ve(t);
  7041. }
  7042. le(t) {
  7043. this.$e.Se(t);
  7044. }
  7045. ae() {
  7046. this.$e.Ne();
  7047. }
  7048. }
  7049. class yr {
  7050. constructor(t) {
  7051. this.$e = t;
  7052. }
  7053. we(t) {
  7054. this.$e.Re(t);
  7055. }
  7056. fe(t) {
  7057. this.$e.Ve(t);
  7058. }
  7059. le(t) {
  7060. this.$e.xe(t);
  7061. }
  7062. ae() {
  7063. this.$e.Oe();
  7064. }
  7065. }
  7066. /**
  7067. * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the
  7068. * actual encoding.
  7069. */ class pr {
  7070. constructor() {
  7071. this.$e = new mr, this.Be = new gr(this.$e), this.Le = new yr(this.$e);
  7072. }
  7073. seed(t) {
  7074. this.$e.seed(t);
  7075. }
  7076. qe(t) {
  7077. return 0 /* IndexKind.ASCENDING */ === t ? this.Be : this.Le;
  7078. }
  7079. Fe() {
  7080. return this.$e.Fe();
  7081. }
  7082. reset() {
  7083. this.$e.reset();
  7084. }
  7085. }
  7086. /**
  7087. * @license
  7088. * Copyright 2022 Google LLC
  7089. *
  7090. * Licensed under the Apache License, Version 2.0 (the "License");
  7091. * you may not use this file except in compliance with the License.
  7092. * You may obtain a copy of the License at
  7093. *
  7094. * http://www.apache.org/licenses/LICENSE-2.0
  7095. *
  7096. * Unless required by applicable law or agreed to in writing, software
  7097. * distributed under the License is distributed on an "AS IS" BASIS,
  7098. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7099. * See the License for the specific language governing permissions and
  7100. * limitations under the License.
  7101. */
  7102. /** Represents an index entry saved by the SDK in persisted storage. */ class Ir {
  7103. constructor(t, e, n, s) {
  7104. this.indexId = t, this.documentKey = e, this.arrayValue = n, this.directionalValue = s;
  7105. }
  7106. /**
  7107. * Returns an IndexEntry entry that sorts immediately after the current
  7108. * directional value.
  7109. */ Ue() {
  7110. const t = this.directionalValue.length, e = 0 === t || 255 === this.directionalValue[t - 1] ? t + 1 : t, n = new Uint8Array(e);
  7111. return n.set(this.directionalValue, 0), e !== t ? n.set([ 0 ], this.directionalValue.length) : ++n[n.length - 1],
  7112. new Ir(this.indexId, this.documentKey, this.arrayValue, n);
  7113. }
  7114. }
  7115. function Tr(t, e) {
  7116. let n = t.indexId - e.indexId;
  7117. return 0 !== n ? n : (n = Er(t.arrayValue, e.arrayValue), 0 !== n ? n : (n = Er(t.directionalValue, e.directionalValue),
  7118. 0 !== n ? n : ct.comparator(t.documentKey, e.documentKey)));
  7119. }
  7120. function Er(t, e) {
  7121. for (let n = 0; n < t.length && n < e.length; ++n) {
  7122. const s = t[n] - e[n];
  7123. if (0 !== s) return s;
  7124. }
  7125. return t.length - e.length;
  7126. }
  7127. /**
  7128. * @license
  7129. * Copyright 2022 Google LLC
  7130. *
  7131. * Licensed under the Apache License, Version 2.0 (the "License");
  7132. * you may not use this file except in compliance with the License.
  7133. * You may obtain a copy of the License at
  7134. *
  7135. * http://www.apache.org/licenses/LICENSE-2.0
  7136. *
  7137. * Unless required by applicable law or agreed to in writing, software
  7138. * distributed under the License is distributed on an "AS IS" BASIS,
  7139. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7140. * See the License for the specific language governing permissions and
  7141. * limitations under the License.
  7142. */
  7143. /**
  7144. * A light query planner for Firestore.
  7145. *
  7146. * This class matches a `FieldIndex` against a Firestore Query `Target`. It
  7147. * determines whether a given index can be used to serve the specified target.
  7148. *
  7149. * The following table showcases some possible index configurations:
  7150. *
  7151. * Query | Index
  7152. * -----------------------------------------------------------------------------
  7153. * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC
  7154. * where('a', '==', 'a').where('b', '==', 'b') | a ASC
  7155. * where('a', '==', 'a').where('b', '==', 'b') | b DESC
  7156. * where('a', '>=', 'a').orderBy('a') | a ASC
  7157. * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC
  7158. * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC
  7159. * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC
  7160. * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING
  7161. * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS
  7162. */ class Ar {
  7163. constructor(t) {
  7164. this.collectionId = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment(),
  7165. this.Ke = t.orderBy, this.Ge = [];
  7166. for (const e of t.filters) {
  7167. const t = e;
  7168. t.isInequality() ? this.Qe = t : this.Ge.push(t);
  7169. }
  7170. }
  7171. /**
  7172. * Returns whether the index can be used to serve the TargetIndexMatcher's
  7173. * target.
  7174. *
  7175. * An index is considered capable of serving the target when:
  7176. * - The target uses all index segments for its filters and orderBy clauses.
  7177. * The target can have additional filter and orderBy clauses, but not
  7178. * fewer.
  7179. * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also
  7180. * have a corresponding `CONTAINS` segment.
  7181. * - All directional index segments can be mapped to the target as a series of
  7182. * equality filters, a single inequality filter and a series of orderBy
  7183. * clauses.
  7184. * - The segments that represent the equality filters may appear out of order.
  7185. * - The optional segment for the inequality filter must appear after all
  7186. * equality segments.
  7187. * - The segments that represent that orderBy clause of the target must appear
  7188. * in order after all equality and inequality segments. Single orderBy
  7189. * clauses cannot be skipped, but a continuous orderBy suffix may be
  7190. * omitted.
  7191. */ je(t) {
  7192. M(t.collectionGroup === this.collectionId);
  7193. // If there is an array element, find a matching filter.
  7194. const e = ht(t);
  7195. if (void 0 !== e && !this.We(e)) return !1;
  7196. const n = lt(t);
  7197. let s = 0, i = 0;
  7198. // Process all equalities first. Equalities can appear out of order.
  7199. for (;s < n.length && this.We(n[s]); ++s) ;
  7200. // If we already have processed all segments, all segments are used to serve
  7201. // the equality filters and we do not need to map any segments to the
  7202. // target's inequality and orderBy clauses.
  7203. if (s === n.length) return !0;
  7204. // If there is an inequality filter, the next segment must match both the
  7205. // filter and the first orderBy clause.
  7206. if (void 0 !== this.Qe) {
  7207. const t = n[s];
  7208. if (!this.ze(this.Qe, t) || !this.He(this.Ke[i++], t)) return !1;
  7209. ++s;
  7210. }
  7211. // All remaining segments need to represent the prefix of the target's
  7212. // orderBy.
  7213. for (;s < n.length; ++s) {
  7214. const t = n[s];
  7215. if (i >= this.Ke.length || !this.He(this.Ke[i++], t)) return !1;
  7216. }
  7217. return !0;
  7218. }
  7219. We(t) {
  7220. for (const e of this.Ge) if (this.ze(e, t)) return !0;
  7221. return !1;
  7222. }
  7223. ze(t, e) {
  7224. if (void 0 === t || !t.field.isEqual(e.fieldPath)) return !1;
  7225. const n = "array-contains" /* Operator.ARRAY_CONTAINS */ === t.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t.op;
  7226. return 2 /* IndexKind.CONTAINS */ === e.kind === n;
  7227. }
  7228. He(t, e) {
  7229. 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);
  7230. }
  7231. }
  7232. /**
  7233. * @license
  7234. * Copyright 2022 Google LLC
  7235. *
  7236. * Licensed under the Apache License, Version 2.0 (the "License");
  7237. * you may not use this file except in compliance with the License.
  7238. * You may obtain a copy of the License at
  7239. *
  7240. * http://www.apache.org/licenses/LICENSE-2.0
  7241. *
  7242. * Unless required by applicable law or agreed to in writing, software
  7243. * distributed under the License is distributed on an "AS IS" BASIS,
  7244. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7245. * See the License for the specific language governing permissions and
  7246. * limitations under the License.
  7247. */
  7248. /**
  7249. * Provides utility functions that help with boolean logic transformations needed for handling
  7250. * complex filters used in queries.
  7251. */
  7252. /**
  7253. * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in
  7254. * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given
  7255. * input into a disjunction of equality filters and returns the expanded filter.
  7256. */ function Rr(t) {
  7257. var e, n;
  7258. if (M(t instanceof Re || t instanceof be), t instanceof Re) {
  7259. if (t instanceof Be) {
  7260. const s = (null === (n = null === (e = t.value.arrayValue) || void 0 === e ? void 0 : e.values) || void 0 === n ? void 0 : n.map((e => Re.create(t.field, "==" /* Operator.EQUAL */ , e)))) || [];
  7261. return be.create(s, "or" /* CompositeOperator.OR */);
  7262. }
  7263. // We have reached other kinds of field filters.
  7264. return t;
  7265. }
  7266. // We have a composite filter.
  7267. const s = t.filters.map((t => Rr(t)));
  7268. return be.create(s, t.op);
  7269. }
  7270. /**
  7271. * Given a composite filter, returns the list of terms in its disjunctive normal form.
  7272. *
  7273. * <p>Each element in the return value is one term of the resulting DNF. For instance: For the
  7274. * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list
  7275. * with two elements: a composite filter that performs (A && C), and a composite filter that
  7276. * performs (B && C).
  7277. *
  7278. * @param filter the composite filter to calculate DNF transform for.
  7279. * @return the terms in the DNF transform.
  7280. */ function br(t) {
  7281. if (0 === t.getFilters().length) return [];
  7282. const e = Sr(Rr(t));
  7283. return M(Vr(e)), Pr(e) || vr(e) ? [ e ] : e.getFilters();
  7284. }
  7285. /** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function Pr(t) {
  7286. return t instanceof Re;
  7287. }
  7288. /**
  7289. * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10
  7290. * && b == 20)
  7291. */ function vr(t) {
  7292. return t instanceof be && Ve(t);
  7293. }
  7294. /**
  7295. * Returns whether or not the given filter is in disjunctive normal form (DNF).
  7296. *
  7297. * <p>In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical
  7298. * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.
  7299. *
  7300. * <p>For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form
  7301. */ function Vr(t) {
  7302. return Pr(t) || vr(t) ||
  7303. /**
  7304. * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and
  7305. * field filters. e.g. (a == 10) || (b==20 && c==30)
  7306. */
  7307. function(t) {
  7308. if (t instanceof be && ve(t)) {
  7309. for (const e of t.getFilters()) if (!Pr(e) && !vr(e)) return !1;
  7310. return !0;
  7311. }
  7312. return !1;
  7313. }(t);
  7314. }
  7315. function Sr(t) {
  7316. if (M(t instanceof Re || t instanceof be), t instanceof Re) return t;
  7317. if (1 === t.filters.length) return Sr(t.filters[0]);
  7318. // Compute DNF for each of the subfilters first
  7319. const e = t.filters.map((t => Sr(t)));
  7320. let n = be.create(e, t.op);
  7321. return n = xr(n), Vr(n) ? n : (M(n instanceof be), M(Pe(n)), M(n.filters.length > 1),
  7322. n.filters.reduce(((t, e) => Dr(t, e))));
  7323. }
  7324. function Dr(t, e) {
  7325. let n;
  7326. return M(t instanceof Re || t instanceof be), M(e instanceof Re || e instanceof be),
  7327. // FieldFilter FieldFilter
  7328. n = t instanceof Re ? e instanceof Re ? function(t, e) {
  7329. // Conjunction distribution for two field filters is the conjunction of them.
  7330. return be.create([ t, e ], "and" /* CompositeOperator.AND */);
  7331. }(t, e) : Cr(t, e) : e instanceof Re ? Cr(e, t) : function(t, e) {
  7332. // There are four cases:
  7333. // (A & B) & (C & D) --> (A & B & C & D)
  7334. // (A & B) & (C | D) --> (A & B & C) | (A & B & D)
  7335. // (A | B) & (C & D) --> (C & D & A) | (C & D & B)
  7336. // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)
  7337. // Case 1 is a merge.
  7338. if (M(t.filters.length > 0 && e.filters.length > 0), Pe(t) && Pe(e)) return xe(t, e.getFilters());
  7339. // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases
  7340. // we should take each element of the disjunction and distribute it over the other side, and
  7341. // return the disjunction of the distribution results.
  7342. const n = ve(t) ? t : e, s = ve(t) ? e : t, i = n.filters.map((t => Dr(t, s)));
  7343. return be.create(i, "or" /* CompositeOperator.OR */);
  7344. }(t, e), xr(n);
  7345. }
  7346. function Cr(t, e) {
  7347. // There are two cases:
  7348. // A & (B & C) --> (A & B & C)
  7349. // A & (B | C) --> (A & B) | (A & C)
  7350. if (Pe(e))
  7351. // Case 1
  7352. return xe(e, t.getFilters());
  7353. {
  7354. // Case 2
  7355. const n = e.filters.map((e => Dr(t, e)));
  7356. return be.create(n, "or" /* CompositeOperator.OR */);
  7357. }
  7358. }
  7359. /**
  7360. * Applies the associativity property to the given filter and returns the resulting filter.
  7361. *
  7362. * <ul>
  7363. * <li>A | (B | C) == (A | B) | C == (A | B | C)
  7364. * <li>A & (B & C) == (A & B) & C == (A & B & C)
  7365. * </ul>
  7366. *
  7367. * <p>For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic
  7368. */ function xr(t) {
  7369. if (M(t instanceof Re || t instanceof be), t instanceof Re) return t;
  7370. const e = t.getFilters();
  7371. // If the composite filter only contains 1 filter, apply associativity to it.
  7372. if (1 === e.length) return xr(e[0]);
  7373. // Associativity applied to a flat composite filter results is itself.
  7374. if (Se(t)) return t;
  7375. // First apply associativity to all subfilters. This will in turn recursively apply
  7376. // associativity to all nested composite filters and field filters.
  7377. const n = e.map((t => xr(t))), s = [];
  7378. // For composite subfilters that perform the same kind of logical operation as `compositeFilter`
  7379. // take out their filters and add them to `compositeFilter`. For example:
  7380. // compositeFilter = (A | (B | C | D))
  7381. // compositeSubfilter = (B | C | D)
  7382. // Result: (A | B | C | D)
  7383. // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been
  7384. // added to the top-level "compositeFilter".
  7385. return n.forEach((e => {
  7386. e instanceof Re ? s.push(e) : e instanceof be && (e.op === t.op ?
  7387. // compositeFilter: (A | (B | C))
  7388. // compositeSubfilter: (B | C)
  7389. // Result: (A | B | C)
  7390. s.push(...e.filters) :
  7391. // compositeFilter: (A | (B & C))
  7392. // compositeSubfilter: (B & C)
  7393. // Result: (A | (B & C))
  7394. s.push(e));
  7395. })), 1 === s.length ? s[0] : be.create(s, t.op);
  7396. }
  7397. /**
  7398. * @license
  7399. * Copyright 2019 Google LLC
  7400. *
  7401. * Licensed under the Apache License, Version 2.0 (the "License");
  7402. * you may not use this file except in compliance with the License.
  7403. * You may obtain a copy of the License at
  7404. *
  7405. * http://www.apache.org/licenses/LICENSE-2.0
  7406. *
  7407. * Unless required by applicable law or agreed to in writing, software
  7408. * distributed under the License is distributed on an "AS IS" BASIS,
  7409. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7410. * See the License for the specific language governing permissions and
  7411. * limitations under the License.
  7412. */
  7413. /**
  7414. * An in-memory implementation of IndexManager.
  7415. */ class Nr {
  7416. constructor() {
  7417. this.Je = new kr;
  7418. }
  7419. addToCollectionParentIndex(t, e) {
  7420. return this.Je.add(e), At.resolve();
  7421. }
  7422. getCollectionParents(t, e) {
  7423. return At.resolve(this.Je.getEntries(e));
  7424. }
  7425. addFieldIndex(t, e) {
  7426. // Field indices are not supported with memory persistence.
  7427. return At.resolve();
  7428. }
  7429. deleteFieldIndex(t, e) {
  7430. // Field indices are not supported with memory persistence.
  7431. return At.resolve();
  7432. }
  7433. getDocumentsMatchingTarget(t, e) {
  7434. // Field indices are not supported with memory persistence.
  7435. return At.resolve(null);
  7436. }
  7437. getIndexType(t, e) {
  7438. // Field indices are not supported with memory persistence.
  7439. return At.resolve(0 /* IndexType.NONE */);
  7440. }
  7441. getFieldIndexes(t, e) {
  7442. // Field indices are not supported with memory persistence.
  7443. return At.resolve([]);
  7444. }
  7445. getNextCollectionGroupToUpdate(t) {
  7446. // Field indices are not supported with memory persistence.
  7447. return At.resolve(null);
  7448. }
  7449. getMinOffset(t, e) {
  7450. return At.resolve(yt.min());
  7451. }
  7452. getMinOffsetFromCollectionGroup(t, e) {
  7453. return At.resolve(yt.min());
  7454. }
  7455. updateCollectionGroup(t, e, n) {
  7456. // Field indices are not supported with memory persistence.
  7457. return At.resolve();
  7458. }
  7459. updateIndexEntries(t, e) {
  7460. // Field indices are not supported with memory persistence.
  7461. return At.resolve();
  7462. }
  7463. }
  7464. /**
  7465. * Internal implementation of the collection-parent index exposed by MemoryIndexManager.
  7466. * Also used for in-memory caching by IndexedDbIndexManager and initial index population
  7467. * in indexeddb_schema.ts
  7468. */ class kr {
  7469. constructor() {
  7470. this.index = {};
  7471. }
  7472. // Returns false if the entry already existed.
  7473. add(t) {
  7474. const e = t.lastSegment(), n = t.popLast(), s = this.index[e] || new We(rt.comparator), i = !s.has(n);
  7475. return this.index[e] = s.add(n), i;
  7476. }
  7477. has(t) {
  7478. const e = t.lastSegment(), n = t.popLast(), s = this.index[e];
  7479. return s && s.has(n);
  7480. }
  7481. getEntries(t) {
  7482. return (this.index[t] || new We(rt.comparator)).toArray();
  7483. }
  7484. }
  7485. /**
  7486. * @license
  7487. * Copyright 2019 Google LLC
  7488. *
  7489. * Licensed under the Apache License, Version 2.0 (the "License");
  7490. * you may not use this file except in compliance with the License.
  7491. * You may obtain a copy of the License at
  7492. *
  7493. * http://www.apache.org/licenses/LICENSE-2.0
  7494. *
  7495. * Unless required by applicable law or agreed to in writing, software
  7496. * distributed under the License is distributed on an "AS IS" BASIS,
  7497. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7498. * See the License for the specific language governing permissions and
  7499. * limitations under the License.
  7500. */ const Or = new Uint8Array(0);
  7501. /**
  7502. * A persisted implementation of IndexManager.
  7503. *
  7504. * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index
  7505. * data as it supports multi-tab access.
  7506. */
  7507. class Mr {
  7508. constructor(t, e) {
  7509. this.user = t, this.databaseId = e,
  7510. /**
  7511. * An in-memory copy of the index entries we've already written since the SDK
  7512. * launched. Used to avoid re-writing the same entry repeatedly.
  7513. *
  7514. * This is *NOT* a complete cache of what's in persistence and so can never be
  7515. * used to satisfy reads.
  7516. */
  7517. this.Ye = new kr,
  7518. /**
  7519. * Maps from a target to its equivalent list of sub-targets. Each sub-target
  7520. * contains only one term from the target's disjunctive normal form (DNF).
  7521. */
  7522. this.Xe = new ls((t => nn(t)), ((t, e) => sn(t, e))), this.uid = t.uid || "";
  7523. }
  7524. /**
  7525. * Adds a new entry to the collection parent index.
  7526. *
  7527. * Repeated calls for the same collectionPath should be avoided within a
  7528. * transaction as IndexedDbIndexManager only caches writes once a transaction
  7529. * has been committed.
  7530. */ addToCollectionParentIndex(t, e) {
  7531. if (!this.Ye.has(e)) {
  7532. const n = e.lastSegment(), s = e.popLast();
  7533. t.addOnCommittedListener((() => {
  7534. // Add the collection to the in memory cache only if the transaction was
  7535. // successfully committed.
  7536. this.Ye.add(e);
  7537. }));
  7538. const i = {
  7539. collectionId: n,
  7540. parent: mi(s)
  7541. };
  7542. return Fr(t).put(i);
  7543. }
  7544. return At.resolve();
  7545. }
  7546. getCollectionParents(t, e) {
  7547. const n = [], s = IDBKeyRange.bound([ e, "" ], [ et(e), "" ],
  7548. /*lowerOpen=*/ !1,
  7549. /*upperOpen=*/ !0);
  7550. return Fr(t).W(s).next((t => {
  7551. for (const s of t) {
  7552. // This collectionId guard shouldn't be necessary (and isn't as long
  7553. // as we're running in a real browser), but there's a bug in
  7554. // indexeddbshim that breaks our range in our tests running in node:
  7555. // https://github.com/axemclion/IndexedDBShim/issues/334
  7556. if (s.collectionId !== e) break;
  7557. n.push(pi(s.parent));
  7558. }
  7559. return n;
  7560. }));
  7561. }
  7562. addFieldIndex(t, e) {
  7563. // TODO(indexing): Verify that the auto-incrementing index ID works in
  7564. // Safari & Firefox.
  7565. const n = Br(t), s = function(t) {
  7566. return {
  7567. indexId: t.indexId,
  7568. collectionGroup: t.collectionGroup,
  7569. fields: t.fields.map((t => [ t.fieldPath.canonicalString(), t.kind ]))
  7570. };
  7571. }(e);
  7572. delete s.indexId;
  7573. // `indexId` is auto-populated by IndexedDb
  7574. const i = n.add(s);
  7575. if (e.indexState) {
  7576. const n = Lr(t);
  7577. return i.next((t => {
  7578. n.put(ur(t, this.user, e.indexState.sequenceNumber, e.indexState.offset));
  7579. }));
  7580. }
  7581. return i.next();
  7582. }
  7583. deleteFieldIndex(t, e) {
  7584. const n = Br(t), s = Lr(t), i = $r(t);
  7585. return n.delete(e.indexId).next((() => s.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ],
  7586. /*lowerOpen=*/ !1,
  7587. /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ],
  7588. /*lowerOpen=*/ !1,
  7589. /*upperOpen=*/ !0))));
  7590. }
  7591. getDocumentsMatchingTarget(t, e) {
  7592. const n = $r(t);
  7593. let s = !0;
  7594. const i = new Map;
  7595. return At.forEach(this.Ze(e), (e => this.tn(t, e).next((t => {
  7596. s && (s = !!t), i.set(e, t);
  7597. })))).next((() => {
  7598. if (s) {
  7599. let t = Es();
  7600. const s = [];
  7601. return At.forEach(i, ((i, r) => {
  7602. var o;
  7603. C("IndexedDbIndexManager", `Using index ${o = i, `id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map((t => `${t.fieldPath}:${t.kind}`)).join(",")}`} to execute ${nn(e)}`);
  7604. const u = function(t, e) {
  7605. const n = ht(e);
  7606. if (void 0 === n) return null;
  7607. for (const e of on(t, n.fieldPath)) switch (e.op) {
  7608. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  7609. return e.value.arrayValue.values || [];
  7610. case "array-contains" /* Operator.ARRAY_CONTAINS */ :
  7611. return [ e.value ];
  7612. // Remaining filters are not array filters.
  7613. }
  7614. return null;
  7615. }
  7616. /**
  7617. * Returns the list of values that are used in != or NOT_IN filters. Returns
  7618. * `null` if there are no such filters.
  7619. */ (r, i), c = function(t, e) {
  7620. const n = new Map;
  7621. for (const s of lt(e)) for (const e of on(t, s.fieldPath)) switch (e.op) {
  7622. case "==" /* Operator.EQUAL */ :
  7623. case "in" /* Operator.IN */ :
  7624. // Encode equality prefix, which is encoded in the index value before
  7625. // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
  7626. // `value != 'ab'`).
  7627. n.set(s.fieldPath.canonicalString(), e.value);
  7628. break;
  7629. case "not-in" /* Operator.NOT_IN */ :
  7630. case "!=" /* Operator.NOT_EQUAL */ :
  7631. // NotIn/NotEqual is always a suffix. There cannot be any remaining
  7632. // segments and hence we can return early here.
  7633. return n.set(s.fieldPath.canonicalString(), e.value), Array.from(n.values());
  7634. // Remaining filters cannot be used as notIn bounds.
  7635. }
  7636. return null;
  7637. }
  7638. /**
  7639. * Returns a lower bound of field values that can be used as a starting point to
  7640. * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound
  7641. * exists.
  7642. */ (r, i), a = function(t, e) {
  7643. const n = [];
  7644. let s = !0;
  7645. // For each segment, retrieve a lower bound if there is a suitable filter or
  7646. // startAt.
  7647. for (const i of lt(e)) {
  7648. const e = 0 /* IndexKind.ASCENDING */ === i.kind ? un(t, i.fieldPath, t.startAt) : cn(t, i.fieldPath, t.startAt);
  7649. n.push(e.value), s && (s = e.inclusive);
  7650. }
  7651. return new Ie(n, s);
  7652. }
  7653. /**
  7654. * Returns an upper bound of field values that can be used as an ending point
  7655. * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no
  7656. * upper bound exists.
  7657. */ (r, i), h = function(t, e) {
  7658. const n = [];
  7659. let s = !0;
  7660. // For each segment, retrieve an upper bound if there is a suitable filter or
  7661. // endAt.
  7662. for (const i of lt(e)) {
  7663. const e = 0 /* IndexKind.ASCENDING */ === i.kind ? cn(t, i.fieldPath, t.endAt) : un(t, i.fieldPath, t.endAt);
  7664. n.push(e.value), s && (s = e.inclusive);
  7665. }
  7666. return new Ie(n, s);
  7667. }(r, i), l = this.en(i, r, a), f = this.en(i, r, h), d = this.nn(i, r, c), _ = this.sn(i.indexId, u, l, a.inclusive, f, h.inclusive, d);
  7668. return At.forEach(_, (i => n.J(i, e.limit).next((e => {
  7669. e.forEach((e => {
  7670. const n = ct.fromSegments(e.documentKey);
  7671. t.has(n) || (t = t.add(n), s.push(n));
  7672. }));
  7673. }))));
  7674. })).next((() => s));
  7675. }
  7676. return At.resolve(null);
  7677. }));
  7678. }
  7679. Ze(t) {
  7680. let e = this.Xe.get(t);
  7681. if (e) return e;
  7682. if (0 === t.filters.length) e = [ t ]; else {
  7683. e = br(be.create(t.filters, "and" /* CompositeOperator.AND */)).map((e => en(t.path, t.collectionGroup, t.orderBy, e.getFilters(), t.limit, t.startAt, t.endAt)));
  7684. }
  7685. return this.Xe.set(t, e), e;
  7686. }
  7687. /**
  7688. * Constructs a key range query on `DbIndexEntryStore` that unions all
  7689. * bounds.
  7690. */ sn(t, e, n, s, i, r, o) {
  7691. // The number of total index scans we union together. This is similar to a
  7692. // distributed normal form, but adapted for array values. We create a single
  7693. // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter
  7694. // combined with the values from the query bounds.
  7695. const u = (null != e ? e.length : 1) * Math.max(n.length, i.length), c = u / (null != e ? e.length : 1), a = [];
  7696. for (let h = 0; h < u; ++h) {
  7697. const u = e ? this.rn(e[h / c]) : Or, l = this.on(t, u, n[h % c], s), f = this.un(t, u, i[h % c], r), d = o.map((e => this.on(t, u, e,
  7698. /* inclusive= */ !0)));
  7699. a.push(...this.createRange(l, f, d));
  7700. }
  7701. return a;
  7702. }
  7703. /** Generates the lower bound for `arrayValue` and `directionalValue`. */ on(t, e, n, s) {
  7704. const i = new Ir(t, ct.empty(), e, n);
  7705. return s ? i : i.Ue();
  7706. }
  7707. /** Generates the upper bound for `arrayValue` and `directionalValue`. */ un(t, e, n, s) {
  7708. const i = new Ir(t, ct.empty(), e, n);
  7709. return s ? i.Ue() : i;
  7710. }
  7711. tn(t, e) {
  7712. const n = new Ar(e), s = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment();
  7713. return this.getFieldIndexes(t, s).next((t => {
  7714. // Return the index with the most number of segments.
  7715. let e = null;
  7716. for (const s of t) {
  7717. n.je(s) && (!e || s.fields.length > e.fields.length) && (e = s);
  7718. }
  7719. return e;
  7720. }));
  7721. }
  7722. getIndexType(t, e) {
  7723. let n = 2 /* IndexType.FULL */;
  7724. const s = this.Ze(e);
  7725. return At.forEach(s, (e => this.tn(t, e).next((t => {
  7726. t ? 0 /* IndexType.NONE */ !== n && t.fields.length < function(t) {
  7727. let e = new We(ut.comparator), n = !1;
  7728. for (const s of t.filters) for (const t of s.getFlattenedFilters())
  7729. // __name__ is not an explicit segment of any index, so we don't need to
  7730. // count it.
  7731. t.field.isKeyField() || (
  7732. // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
  7733. // For instance, it is possible to have an index for "a ARRAY a ASC". Even
  7734. // though these are on the same field, they should be counted as two
  7735. // separate segments in an index.
  7736. "array-contains" /* Operator.ARRAY_CONTAINS */ === t.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t.op ? n = !0 : e = e.add(t.field));
  7737. for (const n of t.orderBy)
  7738. // __name__ is not an explicit segment of any index, so we don't need to
  7739. // count it.
  7740. n.field.isKeyField() || (e = e.add(n.field));
  7741. return e.size + (n ? 1 : 0);
  7742. }(e) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */;
  7743. })))).next((() =>
  7744. // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider
  7745. // OR queries that have a `limit` to have a partial index. For such queries we perform sorting
  7746. // and apply the limit in memory as a post-processing step.
  7747. function(t) {
  7748. return null !== t.limit;
  7749. }(e) && s.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n));
  7750. }
  7751. /**
  7752. * Returns the byte encoded form of the directional values in the field index.
  7753. * Returns `null` if the document does not have all fields specified in the
  7754. * index.
  7755. */ cn(t, e) {
  7756. const n = new pr;
  7757. for (const s of lt(t)) {
  7758. const t = e.data.field(s.fieldPath);
  7759. if (null == t) return null;
  7760. const i = n.qe(s.kind);
  7761. dr.Ie.ue(t, i);
  7762. }
  7763. return n.Fe();
  7764. }
  7765. /** Encodes a single value to the ascending index format. */ rn(t) {
  7766. const e = new pr;
  7767. return dr.Ie.ue(t, e.qe(0 /* IndexKind.ASCENDING */)), e.Fe();
  7768. }
  7769. /**
  7770. * Returns an encoded form of the document key that sorts based on the key
  7771. * ordering of the field index.
  7772. */ an(t, e) {
  7773. const n = new pr;
  7774. return dr.Ie.ue(ce(this.databaseId, e), n.qe(function(t) {
  7775. const e = lt(t);
  7776. return 0 === e.length ? 0 /* IndexKind.ASCENDING */ : e[e.length - 1].kind;
  7777. }(t))), n.Fe();
  7778. }
  7779. /**
  7780. * Encodes the given field values according to the specification in `target`.
  7781. * For IN queries, a list of possible values is returned.
  7782. */ nn(t, e, n) {
  7783. if (null === n) return [];
  7784. let s = [];
  7785. s.push(new pr);
  7786. let i = 0;
  7787. for (const r of lt(t)) {
  7788. const t = n[i++];
  7789. for (const n of s) if (this.hn(e, r.fieldPath) && he(t)) s = this.ln(s, r, t); else {
  7790. const e = n.qe(r.kind);
  7791. dr.Ie.ue(t, e);
  7792. }
  7793. }
  7794. return this.fn(s);
  7795. }
  7796. /**
  7797. * Encodes the given bounds according to the specification in `target`. For IN
  7798. * queries, a list of possible values is returned.
  7799. */ en(t, e, n) {
  7800. return this.nn(t, e, n.position);
  7801. }
  7802. /** Returns the byte representation for the provided encoders. */ fn(t) {
  7803. const e = [];
  7804. for (let n = 0; n < t.length; ++n) e[n] = t[n].Fe();
  7805. return e;
  7806. }
  7807. /**
  7808. * Creates a separate encoder for each element of an array.
  7809. *
  7810. * The method appends each value to all existing encoders (e.g. filter("a",
  7811. * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A
  7812. * list of new encoders is returned.
  7813. */ ln(t, e, n) {
  7814. const s = [ ...t ], i = [];
  7815. for (const t of n.arrayValue.values || []) for (const n of s) {
  7816. const s = new pr;
  7817. s.seed(n.Fe()), dr.Ie.ue(t, s.qe(e.kind)), i.push(s);
  7818. }
  7819. return i;
  7820. }
  7821. hn(t, e) {
  7822. return !!t.filters.find((t => t instanceof Re && t.field.isEqual(e) && ("in" /* Operator.IN */ === t.op || "not-in" /* Operator.NOT_IN */ === t.op)));
  7823. }
  7824. getFieldIndexes(t, e) {
  7825. const n = Br(t), s = Lr(t);
  7826. return (e ? n.W("collectionGroupIndex", IDBKeyRange.bound(e, e)) : n.W()).next((t => {
  7827. const e = [];
  7828. return At.forEach(t, (t => s.get([ t.indexId, this.uid ]).next((n => {
  7829. e.push(function(t, e) {
  7830. const n = e ? new wt(e.sequenceNumber, new yt(tr(e.readTime), new ct(pi(e.documentKey)), e.largestBatchId)) : wt.empty(), s = t.fields.map((([t, e]) => new dt(ut.fromServerFormat(t), e)));
  7831. return new at(t.indexId, t.collectionGroup, s, n);
  7832. }(t, n));
  7833. })))).next((() => e));
  7834. }));
  7835. }
  7836. getNextCollectionGroupToUpdate(t) {
  7837. return this.getFieldIndexes(t).next((t => 0 === t.length ? null : (t.sort(((t, e) => {
  7838. const n = t.indexState.sequenceNumber - e.indexState.sequenceNumber;
  7839. return 0 !== n ? n : Z(t.collectionGroup, e.collectionGroup);
  7840. })), t[0].collectionGroup)));
  7841. }
  7842. updateCollectionGroup(t, e, n) {
  7843. const s = Br(t), i = Lr(t);
  7844. return this.dn(t).next((t => s.W("collectionGroupIndex", IDBKeyRange.bound(e, e)).next((e => At.forEach(e, (e => i.put(ur(e.indexId, this.user, t, n))))))));
  7845. }
  7846. updateIndexEntries(t, e) {
  7847. // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as
  7848. // it could be used across different IndexedDB transactions. As any cached
  7849. // data might be invalidated by other multi-tab clients, we can only trust
  7850. // data within a single IndexedDB transaction. We therefore add a cache
  7851. // here.
  7852. const n = new Map;
  7853. return At.forEach(e, ((e, s) => {
  7854. const i = n.get(e.collectionGroup);
  7855. return (i ? At.resolve(i) : this.getFieldIndexes(t, e.collectionGroup)).next((i => (n.set(e.collectionGroup, i),
  7856. At.forEach(i, (n => this._n(t, e, n).next((e => {
  7857. const i = this.wn(s, n);
  7858. return e.isEqual(i) ? At.resolve() : this.mn(t, s, n, e, i);
  7859. })))))));
  7860. }));
  7861. }
  7862. gn(t, e, n, s) {
  7863. return $r(t).put({
  7864. indexId: s.indexId,
  7865. uid: this.uid,
  7866. arrayValue: s.arrayValue,
  7867. directionalValue: s.directionalValue,
  7868. orderedDocumentKey: this.an(n, e.key),
  7869. documentKey: e.key.path.toArray()
  7870. });
  7871. }
  7872. yn(t, e, n, s) {
  7873. return $r(t).delete([ s.indexId, this.uid, s.arrayValue, s.directionalValue, this.an(n, e.key), e.key.path.toArray() ]);
  7874. }
  7875. _n(t, e, n) {
  7876. const s = $r(t);
  7877. let i = new We(Tr);
  7878. return s.Z({
  7879. index: "documentKeyIndex",
  7880. range: IDBKeyRange.only([ n.indexId, this.uid, this.an(n, e) ])
  7881. }, ((t, s) => {
  7882. i = i.add(new Ir(n.indexId, e, s.arrayValue, s.directionalValue));
  7883. })).next((() => i));
  7884. }
  7885. /** Creates the index entries for the given document. */ wn(t, e) {
  7886. let n = new We(Tr);
  7887. const s = this.cn(e, t);
  7888. if (null == s) return n;
  7889. const i = ht(e);
  7890. if (null != i) {
  7891. const r = t.data.field(i.fieldPath);
  7892. if (he(r)) for (const i of r.arrayValue.values || []) n = n.add(new Ir(e.indexId, t.key, this.rn(i), s));
  7893. } else n = n.add(new Ir(e.indexId, t.key, Or, s));
  7894. return n;
  7895. }
  7896. /**
  7897. * Updates the index entries for the provided document by deleting entries
  7898. * that are no longer referenced in `newEntries` and adding all newly added
  7899. * entries.
  7900. */ mn(t, e, n, s, i) {
  7901. C("IndexedDbIndexManager", "Updating index entries for document '%s'", e.key);
  7902. const r = [];
  7903. return function(t, e, n, s, i) {
  7904. const r = t.getIterator(), o = e.getIterator();
  7905. let u = He(r), c = He(o);
  7906. // Walk through the two sets at the same time, using the ordering defined by
  7907. // `comparator`.
  7908. for (;u || c; ) {
  7909. let t = !1, e = !1;
  7910. if (u && c) {
  7911. const s = n(u, c);
  7912. s < 0 ?
  7913. // The element was removed if the next element in our ordered
  7914. // walkthrough is only in `before`.
  7915. e = !0 : s > 0 && (
  7916. // The element was added if the next element in our ordered walkthrough
  7917. // is only in `after`.
  7918. t = !0);
  7919. } else null != u ? e = !0 : t = !0;
  7920. t ? (s(c), c = He(o)) : e ? (i(u), u = He(r)) : (u = He(r), c = He(o));
  7921. }
  7922. }(s, i, Tr, (
  7923. /* onAdd= */ s => {
  7924. r.push(this.gn(t, e, n, s));
  7925. }), (
  7926. /* onRemove= */ s => {
  7927. r.push(this.yn(t, e, n, s));
  7928. })), At.waitFor(r);
  7929. }
  7930. dn(t) {
  7931. let e = 1;
  7932. return Lr(t).Z({
  7933. index: "sequenceNumberIndex",
  7934. reverse: !0,
  7935. range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])
  7936. }, ((t, n, s) => {
  7937. s.done(), e = n.sequenceNumber + 1;
  7938. })).next((() => e));
  7939. }
  7940. /**
  7941. * Returns a new set of IDB ranges that splits the existing range and excludes
  7942. * any values that match the `notInValue` from these ranges. As an example,
  7943. * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.
  7944. */ createRange(t, e, n) {
  7945. // The notIn values need to be sorted and unique so that we can return a
  7946. // sorted set of non-overlapping ranges.
  7947. n = n.sort(((t, e) => Tr(t, e))).filter(((t, e, n) => !e || 0 !== Tr(t, n[e - 1])));
  7948. const s = [];
  7949. s.push(t);
  7950. for (const i of n) {
  7951. const n = Tr(i, t), r = Tr(i, e);
  7952. if (0 === n)
  7953. // `notInValue` is the lower bound. We therefore need to raise the bound
  7954. // to the next value.
  7955. s[0] = t.Ue(); else if (n > 0 && r < 0)
  7956. // `notInValue` is in the middle of the range
  7957. s.push(i), s.push(i.Ue()); else if (r > 0)
  7958. // `notInValue` (and all following values) are out of the range
  7959. break;
  7960. }
  7961. s.push(e);
  7962. const i = [];
  7963. for (let t = 0; t < s.length; t += 2) {
  7964. // If we encounter two bounds that will create an unmatchable key range,
  7965. // then we return an empty set of key ranges.
  7966. if (this.pn(s[t], s[t + 1])) return [];
  7967. const e = [ s[t].indexId, this.uid, s[t].arrayValue, s[t].directionalValue, Or, [] ], n = [ s[t + 1].indexId, this.uid, s[t + 1].arrayValue, s[t + 1].directionalValue, Or, [] ];
  7968. i.push(IDBKeyRange.bound(e, n));
  7969. }
  7970. return i;
  7971. }
  7972. pn(t, e) {
  7973. // If lower bound is greater than the upper bound, then the key
  7974. // range can never be matched.
  7975. return Tr(t, e) > 0;
  7976. }
  7977. getMinOffsetFromCollectionGroup(t, e) {
  7978. return this.getFieldIndexes(t, e).next(qr);
  7979. }
  7980. getMinOffset(t, e) {
  7981. return At.mapArray(this.Ze(e), (e => this.tn(t, e).next((t => t || O())))).next(qr);
  7982. }
  7983. }
  7984. /**
  7985. * Helper to get a typed SimpleDbStore for the collectionParents
  7986. * document store.
  7987. */ function Fr(t) {
  7988. return Gi(t, "collectionParents");
  7989. }
  7990. /**
  7991. * Helper to get a typed SimpleDbStore for the index entry object store.
  7992. */ function $r(t) {
  7993. return Gi(t, "indexEntries");
  7994. }
  7995. /**
  7996. * Helper to get a typed SimpleDbStore for the index configuration object store.
  7997. */ function Br(t) {
  7998. return Gi(t, "indexConfiguration");
  7999. }
  8000. /**
  8001. * Helper to get a typed SimpleDbStore for the index state object store.
  8002. */ function Lr(t) {
  8003. return Gi(t, "indexState");
  8004. }
  8005. function qr(t) {
  8006. M(0 !== t.length);
  8007. let e = t[0].indexState.offset, n = e.largestBatchId;
  8008. for (let s = 1; s < t.length; s++) {
  8009. const i = t[s].indexState.offset;
  8010. pt(i, e) < 0 && (e = i), n < i.largestBatchId && (n = i.largestBatchId);
  8011. }
  8012. return new yt(e.readTime, e.documentKey, n);
  8013. }
  8014. /**
  8015. * @license
  8016. * Copyright 2018 Google LLC
  8017. *
  8018. * Licensed under the Apache License, Version 2.0 (the "License");
  8019. * you may not use this file except in compliance with the License.
  8020. * You may obtain a copy of the License at
  8021. *
  8022. * http://www.apache.org/licenses/LICENSE-2.0
  8023. *
  8024. * Unless required by applicable law or agreed to in writing, software
  8025. * distributed under the License is distributed on an "AS IS" BASIS,
  8026. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8027. * See the License for the specific language governing permissions and
  8028. * limitations under the License.
  8029. */ const Ur = {
  8030. didRun: !1,
  8031. sequenceNumbersCollected: 0,
  8032. targetsRemoved: 0,
  8033. documentsRemoved: 0
  8034. };
  8035. class Kr {
  8036. constructor(
  8037. // When we attempt to collect, we will only do so if the cache size is greater than this
  8038. // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.
  8039. t,
  8040. // The percentage of sequence numbers that we will attempt to collect
  8041. e,
  8042. // A cap on the total number of sequence numbers that will be collected. This prevents
  8043. // us from collecting a huge number of sequence numbers if the cache has grown very large.
  8044. n) {
  8045. this.cacheSizeCollectionThreshold = t, this.percentileToCollect = e, this.maximumSequenceNumbersToCollect = n;
  8046. }
  8047. static withCacheSize(t) {
  8048. return new Kr(t, Kr.DEFAULT_COLLECTION_PERCENTILE, Kr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);
  8049. }
  8050. }
  8051. /**
  8052. * @license
  8053. * Copyright 2020 Google LLC
  8054. *
  8055. * Licensed under the Apache License, Version 2.0 (the "License");
  8056. * you may not use this file except in compliance with the License.
  8057. * You may obtain a copy of the License at
  8058. *
  8059. * http://www.apache.org/licenses/LICENSE-2.0
  8060. *
  8061. * Unless required by applicable law or agreed to in writing, software
  8062. * distributed under the License is distributed on an "AS IS" BASIS,
  8063. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8064. * See the License for the specific language governing permissions and
  8065. * limitations under the License.
  8066. */
  8067. /**
  8068. * Delete a mutation batch and the associated document mutations.
  8069. * @returns A PersistencePromise of the document mutations that were removed.
  8070. */
  8071. function Gr(t, e, n) {
  8072. const s = t.store("mutations"), i = t.store("documentMutations"), r = [], o = IDBKeyRange.only(n.batchId);
  8073. let u = 0;
  8074. const c = s.Z({
  8075. range: o
  8076. }, ((t, e, n) => (u++, n.delete())));
  8077. r.push(c.next((() => {
  8078. M(1 === u);
  8079. })));
  8080. const a = [];
  8081. for (const t of n.mutations) {
  8082. const s = Ei(e, t.key.path, n.batchId);
  8083. r.push(i.delete(s)), a.push(t.key);
  8084. }
  8085. return At.waitFor(r).next((() => a));
  8086. }
  8087. /**
  8088. * Returns an approximate size for the given document.
  8089. */ function Qr(t) {
  8090. if (!t) return 0;
  8091. let e;
  8092. if (t.document) e = t.document; else if (t.unknownDocument) e = t.unknownDocument; else {
  8093. if (!t.noDocument) throw O();
  8094. e = t.noDocument;
  8095. }
  8096. return JSON.stringify(e).length;
  8097. }
  8098. /**
  8099. * @license
  8100. * Copyright 2017 Google LLC
  8101. *
  8102. * Licensed under the Apache License, Version 2.0 (the "License");
  8103. * you may not use this file except in compliance with the License.
  8104. * You may obtain a copy of the License at
  8105. *
  8106. * http://www.apache.org/licenses/LICENSE-2.0
  8107. *
  8108. * Unless required by applicable law or agreed to in writing, software
  8109. * distributed under the License is distributed on an "AS IS" BASIS,
  8110. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8111. * See the License for the specific language governing permissions and
  8112. * limitations under the License.
  8113. */
  8114. /** A mutation queue for a specific user, backed by IndexedDB. */ Kr.DEFAULT_COLLECTION_PERCENTILE = 10,
  8115. Kr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, Kr.DEFAULT = new Kr(41943040, Kr.DEFAULT_COLLECTION_PERCENTILE, Kr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),
  8116. Kr.DISABLED = new Kr(-1, 0, 0);
  8117. class jr {
  8118. constructor(
  8119. /**
  8120. * The normalized userId (e.g. null UID => "" userId) used to store /
  8121. * retrieve mutations.
  8122. */
  8123. t, e, n, s) {
  8124. this.userId = t, this.yt = e, this.indexManager = n, this.referenceDelegate = s,
  8125. /**
  8126. * Caches the document keys for pending mutation batches. If the mutation
  8127. * has been removed from IndexedDb, the cached value may continue to
  8128. * be used to retrieve the batch's document keys. To remove a cached value
  8129. * locally, `removeCachedMutationKeys()` should be invoked either directly
  8130. * or through `removeMutationBatches()`.
  8131. *
  8132. * With multi-tab, when the primary client acknowledges or rejects a mutation,
  8133. * this cache is used by secondary clients to invalidate the local
  8134. * view of the documents that were previously affected by the mutation.
  8135. */
  8136. // PORTING NOTE: Multi-tab only.
  8137. this.In = {};
  8138. }
  8139. /**
  8140. * Creates a new mutation queue for the given user.
  8141. * @param user - The user for which to create a mutation queue.
  8142. * @param serializer - The serializer to use when persisting to IndexedDb.
  8143. */ static re(t, e, n, s) {
  8144. // TODO(mcg): Figure out what constraints there are on userIDs
  8145. // In particular, are there any reserved characters? are empty ids allowed?
  8146. // For the moment store these together in the same mutations table assuming
  8147. // that empty userIDs aren't allowed.
  8148. M("" !== t.uid);
  8149. const i = t.isAuthenticated() ? t.uid : "";
  8150. return new jr(i, e, n, s);
  8151. }
  8152. checkEmpty(t) {
  8153. let e = !0;
  8154. const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);
  8155. return zr(t).Z({
  8156. index: "userMutationsIndex",
  8157. range: n
  8158. }, ((t, n, s) => {
  8159. e = !1, s.done();
  8160. })).next((() => e));
  8161. }
  8162. addMutationBatch(t, e, n, s) {
  8163. const i = Hr(t), r = zr(t);
  8164. // The IndexedDb implementation in Chrome (and Firefox) does not handle
  8165. // compound indices that include auto-generated keys correctly. To ensure
  8166. // that the index entry is added correctly in all browsers, we perform two
  8167. // writes: The first write is used to retrieve the next auto-generated Batch
  8168. // ID, and the second write populates the index and stores the actual
  8169. // mutation batch.
  8170. // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972
  8171. // We write an empty object to obtain key
  8172. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  8173. return r.add({}).next((o => {
  8174. M("number" == typeof o);
  8175. const u = new Qi(o, e, n, s), c = function(t, e, n) {
  8176. const s = n.baseMutations.map((e => ti(t.ie, e))), i = n.mutations.map((e => ti(t.ie, e)));
  8177. return {
  8178. userId: e,
  8179. batchId: n.batchId,
  8180. localWriteTimeMs: n.localWriteTime.toMillis(),
  8181. baseMutations: s,
  8182. mutations: i
  8183. };
  8184. }(this.yt, this.userId, u), a = [];
  8185. let h = new We(((t, e) => Z(t.canonicalString(), e.canonicalString())));
  8186. for (const t of s) {
  8187. const e = Ei(this.userId, t.key.path, o);
  8188. h = h.add(t.key.path.popLast()), a.push(r.put(c)), a.push(i.put(e, Ai));
  8189. }
  8190. return h.forEach((e => {
  8191. a.push(this.indexManager.addToCollectionParentIndex(t, e));
  8192. })), t.addOnCommittedListener((() => {
  8193. this.In[o] = u.keys();
  8194. })), At.waitFor(a).next((() => u));
  8195. }));
  8196. }
  8197. lookupMutationBatch(t, e) {
  8198. return zr(t).get(e).next((t => t ? (M(t.userId === this.userId), er(this.yt, t)) : null));
  8199. }
  8200. /**
  8201. * Returns the document keys for the mutation batch with the given batchId.
  8202. * For primary clients, this method returns `null` after
  8203. * `removeMutationBatches()` has been called. Secondary clients return a
  8204. * cached result until `removeCachedMutationKeys()` is invoked.
  8205. */
  8206. // PORTING NOTE: Multi-tab only.
  8207. Tn(t, e) {
  8208. return this.In[e] ? At.resolve(this.In[e]) : this.lookupMutationBatch(t, e).next((t => {
  8209. if (t) {
  8210. const n = t.keys();
  8211. return this.In[e] = n, n;
  8212. }
  8213. return null;
  8214. }));
  8215. }
  8216. getNextMutationBatchAfterBatchId(t, e) {
  8217. const n = e + 1, s = IDBKeyRange.lowerBound([ this.userId, n ]);
  8218. let i = null;
  8219. return zr(t).Z({
  8220. index: "userMutationsIndex",
  8221. range: s
  8222. }, ((t, e, s) => {
  8223. e.userId === this.userId && (M(e.batchId >= n), i = er(this.yt, e)), s.done();
  8224. })).next((() => i));
  8225. }
  8226. getHighestUnacknowledgedBatchId(t) {
  8227. const e = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);
  8228. let n = -1;
  8229. return zr(t).Z({
  8230. index: "userMutationsIndex",
  8231. range: e,
  8232. reverse: !0
  8233. }, ((t, e, s) => {
  8234. n = e.batchId, s.done();
  8235. })).next((() => n));
  8236. }
  8237. getAllMutationBatches(t) {
  8238. const e = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);
  8239. return zr(t).W("userMutationsIndex", e).next((t => t.map((t => er(this.yt, t)))));
  8240. }
  8241. getAllMutationBatchesAffectingDocumentKey(t, e) {
  8242. // Scan the document-mutation index starting with a prefix starting with
  8243. // the given documentKey.
  8244. const n = Ti(this.userId, e.path), s = IDBKeyRange.lowerBound(n), i = [];
  8245. return Hr(t).Z({
  8246. range: s
  8247. }, ((n, s, r) => {
  8248. const [o, u, c] = n, a = pi(u);
  8249. // Only consider rows matching exactly the specific key of
  8250. // interest. Note that because we order by path first, and we
  8251. // order terminators before path separators, we'll encounter all
  8252. // the index rows for documentKey contiguously. In particular, all
  8253. // the rows for documentKey will occur before any rows for
  8254. // documents nested in a subcollection beneath documentKey so we
  8255. // can stop as soon as we hit any such row.
  8256. if (o === this.userId && e.path.isEqual(a))
  8257. // Look up the mutation batch in the store.
  8258. return zr(t).get(c).next((t => {
  8259. if (!t) throw O();
  8260. M(t.userId === this.userId), i.push(er(this.yt, t));
  8261. }));
  8262. r.done();
  8263. })).next((() => i));
  8264. }
  8265. getAllMutationBatchesAffectingDocumentKeys(t, e) {
  8266. let n = new We(Z);
  8267. const s = [];
  8268. return e.forEach((e => {
  8269. const i = Ti(this.userId, e.path), r = IDBKeyRange.lowerBound(i), o = Hr(t).Z({
  8270. range: r
  8271. }, ((t, s, i) => {
  8272. const [r, o, u] = t, c = pi(o);
  8273. // Only consider rows matching exactly the specific key of
  8274. // interest. Note that because we order by path first, and we
  8275. // order terminators before path separators, we'll encounter all
  8276. // the index rows for documentKey contiguously. In particular, all
  8277. // the rows for documentKey will occur before any rows for
  8278. // documents nested in a subcollection beneath documentKey so we
  8279. // can stop as soon as we hit any such row.
  8280. r === this.userId && e.path.isEqual(c) ? n = n.add(u) : i.done();
  8281. }));
  8282. s.push(o);
  8283. })), At.waitFor(s).next((() => this.En(t, n)));
  8284. }
  8285. getAllMutationBatchesAffectingQuery(t, e) {
  8286. const n = e.path, s = n.length + 1, i = Ti(this.userId, n), r = IDBKeyRange.lowerBound(i);
  8287. // Collect up unique batchIDs encountered during a scan of the index. Use a
  8288. // SortedSet to accumulate batch IDs so they can be traversed in order in a
  8289. // scan of the main table.
  8290. let o = new We(Z);
  8291. return Hr(t).Z({
  8292. range: r
  8293. }, ((t, e, i) => {
  8294. const [r, u, c] = t, a = pi(u);
  8295. r === this.userId && n.isPrefixOf(a) ?
  8296. // Rows with document keys more than one segment longer than the
  8297. // query path can't be matches. For example, a query on 'rooms'
  8298. // can't match the document /rooms/abc/messages/xyx.
  8299. // TODO(mcg): we'll need a different scanner when we implement
  8300. // ancestor queries.
  8301. a.length === s && (o = o.add(c)) : i.done();
  8302. })).next((() => this.En(t, o)));
  8303. }
  8304. En(t, e) {
  8305. const n = [], s = [];
  8306. // TODO(rockwood): Implement this using iterate.
  8307. return e.forEach((e => {
  8308. s.push(zr(t).get(e).next((t => {
  8309. if (null === t) throw O();
  8310. M(t.userId === this.userId), n.push(er(this.yt, t));
  8311. })));
  8312. })), At.waitFor(s).next((() => n));
  8313. }
  8314. removeMutationBatch(t, e) {
  8315. return Gr(t.se, this.userId, e).next((n => (t.addOnCommittedListener((() => {
  8316. this.An(e.batchId);
  8317. })), At.forEach(n, (e => this.referenceDelegate.markPotentiallyOrphaned(t, e))))));
  8318. }
  8319. /**
  8320. * Clears the cached keys for a mutation batch. This method should be
  8321. * called by secondary clients after they process mutation updates.
  8322. *
  8323. * Note that this method does not have to be called from primary clients as
  8324. * the corresponding cache entries are cleared when an acknowledged or
  8325. * rejected batch is removed from the mutation queue.
  8326. */
  8327. // PORTING NOTE: Multi-tab only
  8328. An(t) {
  8329. delete this.In[t];
  8330. }
  8331. performConsistencyCheck(t) {
  8332. return this.checkEmpty(t).next((e => {
  8333. if (!e) return At.resolve();
  8334. // Verify that there are no entries in the documentMutations index if
  8335. // the queue is empty.
  8336. const n = IDBKeyRange.lowerBound([ this.userId ]);
  8337. const s = [];
  8338. return Hr(t).Z({
  8339. range: n
  8340. }, ((t, e, n) => {
  8341. if (t[0] === this.userId) {
  8342. const e = pi(t[1]);
  8343. s.push(e);
  8344. } else n.done();
  8345. })).next((() => {
  8346. M(0 === s.length);
  8347. }));
  8348. }));
  8349. }
  8350. containsKey(t, e) {
  8351. return Wr(t, this.userId, e);
  8352. }
  8353. // PORTING NOTE: Multi-tab only (state is held in memory in other clients).
  8354. /** Returns the mutation queue's metadata from IndexedDb. */
  8355. Rn(t) {
  8356. return Jr(t).get(this.userId).next((t => t || {
  8357. userId: this.userId,
  8358. lastAcknowledgedBatchId: -1,
  8359. lastStreamToken: ""
  8360. }));
  8361. }
  8362. }
  8363. /**
  8364. * @returns true if the mutation queue for the given user contains a pending
  8365. * mutation for the given key.
  8366. */ function Wr(t, e, n) {
  8367. const s = Ti(e, n.path), i = s[1], r = IDBKeyRange.lowerBound(s);
  8368. let o = !1;
  8369. return Hr(t).Z({
  8370. range: r,
  8371. X: !0
  8372. }, ((t, n, s) => {
  8373. const [r, u, /*batchID*/ c] = t;
  8374. r === e && u === i && (o = !0), s.done();
  8375. })).next((() => o));
  8376. }
  8377. /** Returns true if any mutation queue contains the given document. */
  8378. /**
  8379. * Helper to get a typed SimpleDbStore for the mutations object store.
  8380. */
  8381. function zr(t) {
  8382. return Gi(t, "mutations");
  8383. }
  8384. /**
  8385. * Helper to get a typed SimpleDbStore for the mutationQueues object store.
  8386. */ function Hr(t) {
  8387. return Gi(t, "documentMutations");
  8388. }
  8389. /**
  8390. * Helper to get a typed SimpleDbStore for the mutationQueues object store.
  8391. */ function Jr(t) {
  8392. return Gi(t, "mutationQueues");
  8393. }
  8394. /**
  8395. * @license
  8396. * Copyright 2017 Google LLC
  8397. *
  8398. * Licensed under the Apache License, Version 2.0 (the "License");
  8399. * you may not use this file except in compliance with the License.
  8400. * You may obtain a copy of the License at
  8401. *
  8402. * http://www.apache.org/licenses/LICENSE-2.0
  8403. *
  8404. * Unless required by applicable law or agreed to in writing, software
  8405. * distributed under the License is distributed on an "AS IS" BASIS,
  8406. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8407. * See the License for the specific language governing permissions and
  8408. * limitations under the License.
  8409. */
  8410. /** Offset to ensure non-overlapping target ids. */
  8411. /**
  8412. * Generates monotonically increasing target IDs for sending targets to the
  8413. * watch stream.
  8414. *
  8415. * The client constructs two generators, one for the target cache, and one for
  8416. * for the sync engine (to generate limbo documents targets). These
  8417. * generators produce non-overlapping IDs (by using even and odd IDs
  8418. * respectively).
  8419. *
  8420. * By separating the target ID space, the query cache can generate target IDs
  8421. * that persist across client restarts, while sync engine can independently
  8422. * generate in-memory target IDs that are transient and can be reused after a
  8423. * restart.
  8424. */
  8425. class Yr {
  8426. constructor(t) {
  8427. this.bn = t;
  8428. }
  8429. next() {
  8430. return this.bn += 2, this.bn;
  8431. }
  8432. static Pn() {
  8433. // The target cache generator must return '2' in its first call to `next()`
  8434. // as there is no differentiation in the protocol layer between an unset
  8435. // number and the number '0'. If we were to sent a target with target ID
  8436. // '0', the backend would consider it unset and replace it with its own ID.
  8437. return new Yr(0);
  8438. }
  8439. static vn() {
  8440. // Sync engine assigns target IDs for limbo document detection.
  8441. return new Yr(-1);
  8442. }
  8443. }
  8444. /**
  8445. * @license
  8446. * Copyright 2017 Google LLC
  8447. *
  8448. * Licensed under the Apache License, Version 2.0 (the "License");
  8449. * you may not use this file except in compliance with the License.
  8450. * You may obtain a copy of the License at
  8451. *
  8452. * http://www.apache.org/licenses/LICENSE-2.0
  8453. *
  8454. * Unless required by applicable law or agreed to in writing, software
  8455. * distributed under the License is distributed on an "AS IS" BASIS,
  8456. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8457. * See the License for the specific language governing permissions and
  8458. * limitations under the License.
  8459. */ class Xr {
  8460. constructor(t, e) {
  8461. this.referenceDelegate = t, this.yt = e;
  8462. }
  8463. // PORTING NOTE: We don't cache global metadata for the target cache, since
  8464. // some of it (in particular `highestTargetId`) can be modified by secondary
  8465. // tabs. We could perhaps be more granular (and e.g. still cache
  8466. // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go
  8467. // to IndexedDb whenever we need to read metadata. We can revisit if it turns
  8468. // out to have a meaningful performance impact.
  8469. allocateTargetId(t) {
  8470. return this.Vn(t).next((e => {
  8471. const n = new Yr(e.highestTargetId);
  8472. return e.highestTargetId = n.next(), this.Sn(t, e).next((() => e.highestTargetId));
  8473. }));
  8474. }
  8475. getLastRemoteSnapshotVersion(t) {
  8476. return this.Vn(t).next((t => st.fromTimestamp(new nt(t.lastRemoteSnapshotVersion.seconds, t.lastRemoteSnapshotVersion.nanoseconds))));
  8477. }
  8478. getHighestSequenceNumber(t) {
  8479. return this.Vn(t).next((t => t.highestListenSequenceNumber));
  8480. }
  8481. setTargetsMetadata(t, e, n) {
  8482. return this.Vn(t).next((s => (s.highestListenSequenceNumber = e, n && (s.lastRemoteSnapshotVersion = n.toTimestamp()),
  8483. e > s.highestListenSequenceNumber && (s.highestListenSequenceNumber = e), this.Sn(t, s))));
  8484. }
  8485. addTargetData(t, e) {
  8486. return this.Dn(t, e).next((() => this.Vn(t).next((n => (n.targetCount += 1, this.Cn(e, n),
  8487. this.Sn(t, n))))));
  8488. }
  8489. updateTargetData(t, e) {
  8490. return this.Dn(t, e);
  8491. }
  8492. removeTargetData(t, e) {
  8493. return this.removeMatchingKeysForTargetId(t, e.targetId).next((() => Zr(t).delete(e.targetId))).next((() => this.Vn(t))).next((e => (M(e.targetCount > 0),
  8494. e.targetCount -= 1, this.Sn(t, e))));
  8495. }
  8496. /**
  8497. * Drops any targets with sequence number less than or equal to the upper bound, excepting those
  8498. * present in `activeTargetIds`. Document associations for the removed targets are also removed.
  8499. * Returns the number of targets removed.
  8500. */ removeTargets(t, e, n) {
  8501. let s = 0;
  8502. const i = [];
  8503. return Zr(t).Z(((r, o) => {
  8504. const u = nr(o);
  8505. u.sequenceNumber <= e && null === n.get(u.targetId) && (s++, i.push(this.removeTargetData(t, u)));
  8506. })).next((() => At.waitFor(i))).next((() => s));
  8507. }
  8508. /**
  8509. * Call provided function with each `TargetData` that we have cached.
  8510. */ forEachTarget(t, e) {
  8511. return Zr(t).Z(((t, n) => {
  8512. const s = nr(n);
  8513. e(s);
  8514. }));
  8515. }
  8516. Vn(t) {
  8517. return to(t).get("targetGlobalKey").next((t => (M(null !== t), t)));
  8518. }
  8519. Sn(t, e) {
  8520. return to(t).put("targetGlobalKey", e);
  8521. }
  8522. Dn(t, e) {
  8523. return Zr(t).put(sr(this.yt, e));
  8524. }
  8525. /**
  8526. * In-place updates the provided metadata to account for values in the given
  8527. * TargetData. Saving is done separately. Returns true if there were any
  8528. * changes to the metadata.
  8529. */ Cn(t, e) {
  8530. let n = !1;
  8531. return t.targetId > e.highestTargetId && (e.highestTargetId = t.targetId, n = !0),
  8532. t.sequenceNumber > e.highestListenSequenceNumber && (e.highestListenSequenceNumber = t.sequenceNumber,
  8533. n = !0), n;
  8534. }
  8535. getTargetCount(t) {
  8536. return this.Vn(t).next((t => t.targetCount));
  8537. }
  8538. getTargetData(t, e) {
  8539. // Iterating by the canonicalId may yield more than one result because
  8540. // canonicalId values are not required to be unique per target. This query
  8541. // depends on the queryTargets index to be efficient.
  8542. const n = nn(e), s = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]);
  8543. let i = null;
  8544. return Zr(t).Z({
  8545. range: s,
  8546. index: "queryTargetsIndex"
  8547. }, ((t, n, s) => {
  8548. const r = nr(n);
  8549. // After finding a potential match, check that the target is
  8550. // actually equal to the requested target.
  8551. sn(e, r.target) && (i = r, s.done());
  8552. })).next((() => i));
  8553. }
  8554. addMatchingKeys(t, e, n) {
  8555. // PORTING NOTE: The reverse index (documentsTargets) is maintained by
  8556. // IndexedDb.
  8557. const s = [], i = eo(t);
  8558. return e.forEach((e => {
  8559. const r = mi(e.path);
  8560. s.push(i.put({
  8561. targetId: n,
  8562. path: r
  8563. })), s.push(this.referenceDelegate.addReference(t, n, e));
  8564. })), At.waitFor(s);
  8565. }
  8566. removeMatchingKeys(t, e, n) {
  8567. // PORTING NOTE: The reverse index (documentsTargets) is maintained by
  8568. // IndexedDb.
  8569. const s = eo(t);
  8570. return At.forEach(e, (e => {
  8571. const i = mi(e.path);
  8572. return At.waitFor([ s.delete([ n, i ]), this.referenceDelegate.removeReference(t, n, e) ]);
  8573. }));
  8574. }
  8575. removeMatchingKeysForTargetId(t, e) {
  8576. const n = eo(t), s = IDBKeyRange.bound([ e ], [ e + 1 ],
  8577. /*lowerOpen=*/ !1,
  8578. /*upperOpen=*/ !0);
  8579. return n.delete(s);
  8580. }
  8581. getMatchingKeysForTargetId(t, e) {
  8582. const n = IDBKeyRange.bound([ e ], [ e + 1 ],
  8583. /*lowerOpen=*/ !1,
  8584. /*upperOpen=*/ !0), s = eo(t);
  8585. let i = Es();
  8586. return s.Z({
  8587. range: n,
  8588. X: !0
  8589. }, ((t, e, n) => {
  8590. const s = pi(t[1]), r = new ct(s);
  8591. i = i.add(r);
  8592. })).next((() => i));
  8593. }
  8594. containsKey(t, e) {
  8595. const n = mi(e.path), s = IDBKeyRange.bound([ n ], [ et(n) ],
  8596. /*lowerOpen=*/ !1,
  8597. /*upperOpen=*/ !0);
  8598. let i = 0;
  8599. return eo(t).Z({
  8600. index: "documentTargetsIndex",
  8601. X: !0,
  8602. range: s
  8603. }, (([t, e], n, s) => {
  8604. // Having a sentinel row for a document does not count as containing that document;
  8605. // For the target cache, containing the document means the document is part of some
  8606. // target.
  8607. 0 !== t && (i++, s.done());
  8608. })).next((() => i > 0));
  8609. }
  8610. /**
  8611. * Looks up a TargetData entry by target ID.
  8612. *
  8613. * @param targetId - The target ID of the TargetData entry to look up.
  8614. * @returns The cached TargetData entry, or null if the cache has no entry for
  8615. * the target.
  8616. */
  8617. // PORTING NOTE: Multi-tab only.
  8618. ne(t, e) {
  8619. return Zr(t).get(e).next((t => t ? nr(t) : null));
  8620. }
  8621. }
  8622. /**
  8623. * Helper to get a typed SimpleDbStore for the queries object store.
  8624. */ function Zr(t) {
  8625. return Gi(t, "targets");
  8626. }
  8627. /**
  8628. * Helper to get a typed SimpleDbStore for the target globals object store.
  8629. */ function to(t) {
  8630. return Gi(t, "targetGlobal");
  8631. }
  8632. /**
  8633. * Helper to get a typed SimpleDbStore for the document target object store.
  8634. */ function eo(t) {
  8635. return Gi(t, "targetDocuments");
  8636. }
  8637. /**
  8638. * @license
  8639. * Copyright 2020 Google LLC
  8640. *
  8641. * Licensed under the Apache License, Version 2.0 (the "License");
  8642. * you may not use this file except in compliance with the License.
  8643. * You may obtain a copy of the License at
  8644. *
  8645. * http://www.apache.org/licenses/LICENSE-2.0
  8646. *
  8647. * Unless required by applicable law or agreed to in writing, software
  8648. * distributed under the License is distributed on an "AS IS" BASIS,
  8649. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8650. * See the License for the specific language governing permissions and
  8651. * limitations under the License.
  8652. */ function no([t, e], [n, s]) {
  8653. const i = Z(t, n);
  8654. return 0 === i ? Z(e, s) : i;
  8655. }
  8656. /**
  8657. * Used to calculate the nth sequence number. Keeps a rolling buffer of the
  8658. * lowest n values passed to `addElement`, and finally reports the largest of
  8659. * them in `maxValue`.
  8660. */ class so {
  8661. constructor(t) {
  8662. this.xn = t, this.buffer = new We(no), this.Nn = 0;
  8663. }
  8664. kn() {
  8665. return ++this.Nn;
  8666. }
  8667. On(t) {
  8668. const e = [ t, this.kn() ];
  8669. if (this.buffer.size < this.xn) this.buffer = this.buffer.add(e); else {
  8670. const t = this.buffer.last();
  8671. no(e, t) < 0 && (this.buffer = this.buffer.delete(t).add(e));
  8672. }
  8673. }
  8674. get maxValue() {
  8675. // Guaranteed to be non-empty. If we decide we are not collecting any
  8676. // sequence numbers, nthSequenceNumber below short-circuits. If we have
  8677. // decided that we are collecting n sequence numbers, it's because n is some
  8678. // percentage of the existing sequence numbers. That means we should never
  8679. // be in a situation where we are collecting sequence numbers but don't
  8680. // actually have any.
  8681. return this.buffer.last()[0];
  8682. }
  8683. }
  8684. /**
  8685. * This class is responsible for the scheduling of LRU garbage collection. It handles checking
  8686. * whether or not GC is enabled, as well as which delay to use before the next run.
  8687. */ class io {
  8688. constructor(t, e, n) {
  8689. this.garbageCollector = t, this.asyncQueue = e, this.localStore = n, this.Mn = null;
  8690. }
  8691. start() {
  8692. -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Fn(6e4);
  8693. }
  8694. stop() {
  8695. this.Mn && (this.Mn.cancel(), this.Mn = null);
  8696. }
  8697. get started() {
  8698. return null !== this.Mn;
  8699. }
  8700. Fn(t) {
  8701. C("LruGarbageCollector", `Garbage collection scheduled in ${t}ms`), this.Mn = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection" /* TimerId.LruGarbageCollection */ , t, (async () => {
  8702. this.Mn = null;
  8703. try {
  8704. await this.localStore.collectGarbage(this.garbageCollector);
  8705. } catch (t) {
  8706. Vt(t) ? C("LruGarbageCollector", "Ignoring IndexedDB error during garbage collection: ", t) : await Et(t);
  8707. }
  8708. await this.Fn(3e5);
  8709. }));
  8710. }
  8711. }
  8712. /** Implements the steps for LRU garbage collection. */ class ro {
  8713. constructor(t, e) {
  8714. this.$n = t, this.params = e;
  8715. }
  8716. calculateTargetCount(t, e) {
  8717. return this.$n.Bn(t).next((t => Math.floor(e / 100 * t)));
  8718. }
  8719. nthSequenceNumber(t, e) {
  8720. if (0 === e) return At.resolve(Ot.at);
  8721. const n = new so(e);
  8722. return this.$n.forEachTarget(t, (t => n.On(t.sequenceNumber))).next((() => this.$n.Ln(t, (t => n.On(t))))).next((() => n.maxValue));
  8723. }
  8724. removeTargets(t, e, n) {
  8725. return this.$n.removeTargets(t, e, n);
  8726. }
  8727. removeOrphanedDocuments(t, e) {
  8728. return this.$n.removeOrphanedDocuments(t, e);
  8729. }
  8730. collect(t, e) {
  8731. return -1 === this.params.cacheSizeCollectionThreshold ? (C("LruGarbageCollector", "Garbage collection skipped; disabled"),
  8732. At.resolve(Ur)) : this.getCacheSize(t).next((n => n < this.params.cacheSizeCollectionThreshold ? (C("LruGarbageCollector", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),
  8733. Ur) : this.qn(t, e)));
  8734. }
  8735. getCacheSize(t) {
  8736. return this.$n.getCacheSize(t);
  8737. }
  8738. qn(t, e) {
  8739. let n, s, i, r, o, c, a;
  8740. const h = Date.now();
  8741. return this.calculateTargetCount(t, this.params.percentileToCollect).next((e => (
  8742. // Cap at the configured max
  8743. e > this.params.maximumSequenceNumbersToCollect ? (C("LruGarbageCollector", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),
  8744. s = this.params.maximumSequenceNumbersToCollect) : s = e, r = Date.now(), this.nthSequenceNumber(t, s)))).next((s => (n = s,
  8745. o = Date.now(), this.removeTargets(t, n, e)))).next((e => (i = e, c = Date.now(),
  8746. this.removeOrphanedDocuments(t, n)))).next((t => {
  8747. if (a = Date.now(), S() <= LogLevel.DEBUG) {
  8748. C("LruGarbageCollector", `LRU Garbage Collection\n\tCounted targets in ${r - h}ms\n\tDetermined least recently used ${s} in ` + (o - r) + "ms\n" + `\tRemoved ${i} targets in ` + (c - o) + "ms\n" + `\tRemoved ${t} documents in ` + (a - c) + "ms\n" + `Total Duration: ${a - h}ms`);
  8749. }
  8750. return At.resolve({
  8751. didRun: !0,
  8752. sequenceNumbersCollected: s,
  8753. targetsRemoved: i,
  8754. documentsRemoved: t
  8755. });
  8756. }));
  8757. }
  8758. }
  8759. /**
  8760. * @license
  8761. * Copyright 2020 Google LLC
  8762. *
  8763. * Licensed under the Apache License, Version 2.0 (the "License");
  8764. * you may not use this file except in compliance with the License.
  8765. * You may obtain a copy of the License at
  8766. *
  8767. * http://www.apache.org/licenses/LICENSE-2.0
  8768. *
  8769. * Unless required by applicable law or agreed to in writing, software
  8770. * distributed under the License is distributed on an "AS IS" BASIS,
  8771. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8772. * See the License for the specific language governing permissions and
  8773. * limitations under the License.
  8774. */
  8775. /** Provides LRU functionality for IndexedDB persistence. */
  8776. class oo {
  8777. constructor(t, e) {
  8778. this.db = t, this.garbageCollector = function(t, e) {
  8779. return new ro(t, e);
  8780. }(this, e);
  8781. }
  8782. Bn(t) {
  8783. const e = this.Un(t);
  8784. return this.db.getTargetCache().getTargetCount(t).next((t => e.next((e => t + e))));
  8785. }
  8786. Un(t) {
  8787. let e = 0;
  8788. return this.Ln(t, (t => {
  8789. e++;
  8790. })).next((() => e));
  8791. }
  8792. forEachTarget(t, e) {
  8793. return this.db.getTargetCache().forEachTarget(t, e);
  8794. }
  8795. Ln(t, e) {
  8796. return this.Kn(t, ((t, n) => e(n)));
  8797. }
  8798. addReference(t, e, n) {
  8799. return uo(t, n);
  8800. }
  8801. removeReference(t, e, n) {
  8802. return uo(t, n);
  8803. }
  8804. removeTargets(t, e, n) {
  8805. return this.db.getTargetCache().removeTargets(t, e, n);
  8806. }
  8807. markPotentiallyOrphaned(t, e) {
  8808. return uo(t, e);
  8809. }
  8810. /**
  8811. * Returns true if anything would prevent this document from being garbage
  8812. * collected, given that the document in question is not present in any
  8813. * targets and has a sequence number less than or equal to the upper bound for
  8814. * the collection run.
  8815. */ Gn(t, e) {
  8816. return function(t, e) {
  8817. let n = !1;
  8818. return Jr(t).tt((s => Wr(t, s, e).next((t => (t && (n = !0), At.resolve(!t)))))).next((() => n));
  8819. }(t, e);
  8820. }
  8821. removeOrphanedDocuments(t, e) {
  8822. const n = this.db.getRemoteDocumentCache().newChangeBuffer(), s = [];
  8823. let i = 0;
  8824. return this.Kn(t, ((r, o) => {
  8825. if (o <= e) {
  8826. const e = this.Gn(t, r).next((e => {
  8827. if (!e)
  8828. // Our size accounting requires us to read all documents before
  8829. // removing them.
  8830. return i++, n.getEntry(t, r).next((() => (n.removeEntry(r, st.min()), eo(t).delete([ 0, mi(r.path) ]))));
  8831. }));
  8832. s.push(e);
  8833. }
  8834. })).next((() => At.waitFor(s))).next((() => n.apply(t))).next((() => i));
  8835. }
  8836. removeTarget(t, e) {
  8837. const n = e.withSequenceNumber(t.currentSequenceNumber);
  8838. return this.db.getTargetCache().updateTargetData(t, n);
  8839. }
  8840. updateLimboDocument(t, e) {
  8841. return uo(t, e);
  8842. }
  8843. /**
  8844. * Call provided function for each document in the cache that is 'orphaned'. Orphaned
  8845. * means not a part of any target, so the only entry in the target-document index for
  8846. * that document will be the sentinel row (targetId 0), which will also have the sequence
  8847. * number for the last time the document was accessed.
  8848. */ Kn(t, e) {
  8849. const n = eo(t);
  8850. let s, i = Ot.at;
  8851. return n.Z({
  8852. index: "documentTargetsIndex"
  8853. }, (([t, n], {path: r, sequenceNumber: o}) => {
  8854. 0 === t ? (
  8855. // if nextToReport is valid, report it, this is a new key so the
  8856. // last one must not be a member of any targets.
  8857. i !== Ot.at && e(new ct(pi(s)), i),
  8858. // set nextToReport to be this sequence number. It's the next one we
  8859. // might report, if we don't find any targets for this document.
  8860. // Note that the sequence number must be defined when the targetId
  8861. // is 0.
  8862. i = o, s = r) :
  8863. // set nextToReport to be invalid, we know we don't need to report
  8864. // this one since we found a target for it.
  8865. i = Ot.at;
  8866. })).next((() => {
  8867. // Since we report sequence numbers after getting to the next key, we
  8868. // need to check if the last key we iterated over was an orphaned
  8869. // document and report it.
  8870. i !== Ot.at && e(new ct(pi(s)), i);
  8871. }));
  8872. }
  8873. getCacheSize(t) {
  8874. return this.db.getRemoteDocumentCache().getSize(t);
  8875. }
  8876. }
  8877. function uo(t, e) {
  8878. return eo(t).put(
  8879. /**
  8880. * @returns A value suitable for writing a sentinel row in the target-document
  8881. * store.
  8882. */
  8883. function(t, e) {
  8884. return {
  8885. targetId: 0,
  8886. path: mi(t.path),
  8887. sequenceNumber: e
  8888. };
  8889. }(e, t.currentSequenceNumber));
  8890. }
  8891. /**
  8892. * @license
  8893. * Copyright 2017 Google LLC
  8894. *
  8895. * Licensed under the Apache License, Version 2.0 (the "License");
  8896. * you may not use this file except in compliance with the License.
  8897. * You may obtain a copy of the License at
  8898. *
  8899. * http://www.apache.org/licenses/LICENSE-2.0
  8900. *
  8901. * Unless required by applicable law or agreed to in writing, software
  8902. * distributed under the License is distributed on an "AS IS" BASIS,
  8903. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8904. * See the License for the specific language governing permissions and
  8905. * limitations under the License.
  8906. */
  8907. /**
  8908. * An in-memory buffer of entries to be written to a RemoteDocumentCache.
  8909. * It can be used to batch up a set of changes to be written to the cache, but
  8910. * additionally supports reading entries back with the `getEntry()` method,
  8911. * falling back to the underlying RemoteDocumentCache if no entry is
  8912. * buffered.
  8913. *
  8914. * Entries added to the cache *must* be read first. This is to facilitate
  8915. * calculating the size delta of the pending changes.
  8916. *
  8917. * PORTING NOTE: This class was implemented then removed from other platforms.
  8918. * If byte-counting ends up being needed on the other platforms, consider
  8919. * porting this class as part of that implementation work.
  8920. */ class co {
  8921. constructor() {
  8922. // A mapping of document key to the new cache entry that should be written.
  8923. this.changes = new ls((t => t.toString()), ((t, e) => t.isEqual(e))), this.changesApplied = !1;
  8924. }
  8925. /**
  8926. * Buffers a `RemoteDocumentCache.addEntry()` call.
  8927. *
  8928. * You can only modify documents that have already been retrieved via
  8929. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  8930. */ addEntry(t) {
  8931. this.assertNotApplied(), this.changes.set(t.key, t);
  8932. }
  8933. /**
  8934. * Buffers a `RemoteDocumentCache.removeEntry()` call.
  8935. *
  8936. * You can only remove documents that have already been retrieved via
  8937. * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
  8938. */ removeEntry(t, e) {
  8939. this.assertNotApplied(), this.changes.set(t, Ze.newInvalidDocument(t).setReadTime(e));
  8940. }
  8941. /**
  8942. * Looks up an entry in the cache. The buffered changes will first be checked,
  8943. * and if no buffered change applies, this will forward to
  8944. * `RemoteDocumentCache.getEntry()`.
  8945. *
  8946. * @param transaction - The transaction in which to perform any persistence
  8947. * operations.
  8948. * @param documentKey - The key of the entry to look up.
  8949. * @returns The cached document or an invalid document if we have nothing
  8950. * cached.
  8951. */ getEntry(t, e) {
  8952. this.assertNotApplied();
  8953. const n = this.changes.get(e);
  8954. return void 0 !== n ? At.resolve(n) : this.getFromCache(t, e);
  8955. }
  8956. /**
  8957. * Looks up several entries in the cache, forwarding to
  8958. * `RemoteDocumentCache.getEntry()`.
  8959. *
  8960. * @param transaction - The transaction in which to perform any persistence
  8961. * operations.
  8962. * @param documentKeys - The keys of the entries to look up.
  8963. * @returns A map of cached documents, indexed by key. If an entry cannot be
  8964. * found, the corresponding key will be mapped to an invalid document.
  8965. */ getEntries(t, e) {
  8966. return this.getAllFromCache(t, e);
  8967. }
  8968. /**
  8969. * Applies buffered changes to the underlying RemoteDocumentCache, using
  8970. * the provided transaction.
  8971. */ apply(t) {
  8972. return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(t);
  8973. }
  8974. /** Helper to assert this.changes is not null */ assertNotApplied() {}
  8975. }
  8976. /**
  8977. * @license
  8978. * Copyright 2017 Google LLC
  8979. *
  8980. * Licensed under the Apache License, Version 2.0 (the "License");
  8981. * you may not use this file except in compliance with the License.
  8982. * You may obtain a copy of the License at
  8983. *
  8984. * http://www.apache.org/licenses/LICENSE-2.0
  8985. *
  8986. * Unless required by applicable law or agreed to in writing, software
  8987. * distributed under the License is distributed on an "AS IS" BASIS,
  8988. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8989. * See the License for the specific language governing permissions and
  8990. * limitations under the License.
  8991. */
  8992. /**
  8993. * The RemoteDocumentCache for IndexedDb. To construct, invoke
  8994. * `newIndexedDbRemoteDocumentCache()`.
  8995. */ class ao {
  8996. constructor(t) {
  8997. this.yt = t;
  8998. }
  8999. setIndexManager(t) {
  9000. this.indexManager = t;
  9001. }
  9002. /**
  9003. * Adds the supplied entries to the cache.
  9004. *
  9005. * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
  9006. * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
  9007. */ addEntry(t, e, n) {
  9008. return _o(t).put(n);
  9009. }
  9010. /**
  9011. * Removes a document from the cache.
  9012. *
  9013. * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
  9014. * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
  9015. */ removeEntry(t, e, n) {
  9016. return _o(t).delete(
  9017. /**
  9018. * Returns a key that can be used for document lookups via the primary key of
  9019. * the DbRemoteDocument object store.
  9020. */
  9021. function(t, e) {
  9022. const n = t.path.toArray();
  9023. return [
  9024. /* prefix path */ n.slice(0, n.length - 2),
  9025. /* collection id */ n[n.length - 2], Xi(e),
  9026. /* document id */ n[n.length - 1] ];
  9027. }
  9028. /**
  9029. * Returns a key that can be used for document lookups on the
  9030. * `DbRemoteDocumentDocumentCollectionGroupIndex` index.
  9031. */ (e, n));
  9032. }
  9033. /**
  9034. * Updates the current cache size.
  9035. *
  9036. * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the
  9037. * cache's metadata.
  9038. */ updateMetadata(t, e) {
  9039. return this.getMetadata(t).next((n => (n.byteSize += e, this.Qn(t, n))));
  9040. }
  9041. getEntry(t, e) {
  9042. let n = Ze.newInvalidDocument(e);
  9043. return _o(t).Z({
  9044. index: "documentKeyIndex",
  9045. range: IDBKeyRange.only(wo(e))
  9046. }, ((t, s) => {
  9047. n = this.jn(e, s);
  9048. })).next((() => n));
  9049. }
  9050. /**
  9051. * Looks up an entry in the cache.
  9052. *
  9053. * @param documentKey - The key of the entry to look up.
  9054. * @returns The cached document entry and its size.
  9055. */ Wn(t, e) {
  9056. let n = {
  9057. size: 0,
  9058. document: Ze.newInvalidDocument(e)
  9059. };
  9060. return _o(t).Z({
  9061. index: "documentKeyIndex",
  9062. range: IDBKeyRange.only(wo(e))
  9063. }, ((t, s) => {
  9064. n = {
  9065. document: this.jn(e, s),
  9066. size: Qr(s)
  9067. };
  9068. })).next((() => n));
  9069. }
  9070. getEntries(t, e) {
  9071. let n = ds();
  9072. return this.zn(t, e, ((t, e) => {
  9073. const s = this.jn(t, e);
  9074. n = n.insert(t, s);
  9075. })).next((() => n));
  9076. }
  9077. /**
  9078. * Looks up several entries in the cache.
  9079. *
  9080. * @param documentKeys - The set of keys entries to look up.
  9081. * @returns A map of documents indexed by key and a map of sizes indexed by
  9082. * key (zero if the document does not exist).
  9083. */ Hn(t, e) {
  9084. let n = ds(), s = new Ge(ct.comparator);
  9085. return this.zn(t, e, ((t, e) => {
  9086. const i = this.jn(t, e);
  9087. n = n.insert(t, i), s = s.insert(t, Qr(e));
  9088. })).next((() => ({
  9089. documents: n,
  9090. Jn: s
  9091. })));
  9092. }
  9093. zn(t, e, n) {
  9094. if (e.isEmpty()) return At.resolve();
  9095. let s = new We(go);
  9096. e.forEach((t => s = s.add(t)));
  9097. const i = IDBKeyRange.bound(wo(s.first()), wo(s.last())), r = s.getIterator();
  9098. let o = r.getNext();
  9099. return _o(t).Z({
  9100. index: "documentKeyIndex",
  9101. range: i
  9102. }, ((t, e, s) => {
  9103. const i = ct.fromSegments([ ...e.prefixPath, e.collectionGroup, e.documentId ]);
  9104. // Go through keys not found in cache.
  9105. for (;o && go(o, i) < 0; ) n(o, null), o = r.getNext();
  9106. o && o.isEqual(i) && (
  9107. // Key found in cache.
  9108. n(o, e), o = r.hasNext() ? r.getNext() : null),
  9109. // Skip to the next key (if there is one).
  9110. o ? s.j(wo(o)) : s.done();
  9111. })).next((() => {
  9112. // The rest of the keys are not in the cache. One case where `iterate`
  9113. // above won't go through them is when the cache is empty.
  9114. for (;o; ) n(o, null), o = r.hasNext() ? r.getNext() : null;
  9115. }));
  9116. }
  9117. getAllFromCollection(t, e, n) {
  9118. const s = [ e.popLast().toArray(), e.lastSegment(), Xi(n.readTime), n.documentKey.path.isEmpty() ? "" : n.documentKey.path.lastSegment() ], i = [ e.popLast().toArray(), e.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], "" ];
  9119. return _o(t).W(IDBKeyRange.bound(s, i, !0)).next((t => {
  9120. let e = ds();
  9121. for (const n of t) {
  9122. const t = this.jn(ct.fromSegments(n.prefixPath.concat(n.collectionGroup, n.documentId)), n);
  9123. e = e.insert(t.key, t);
  9124. }
  9125. return e;
  9126. }));
  9127. }
  9128. getAllFromCollectionGroup(t, e, n, s) {
  9129. let i = ds();
  9130. const r = mo(e, n), o = mo(e, yt.max());
  9131. return _o(t).Z({
  9132. index: "collectionGroupIndex",
  9133. range: IDBKeyRange.bound(r, o, !0)
  9134. }, ((t, e, n) => {
  9135. const r = this.jn(ct.fromSegments(e.prefixPath.concat(e.collectionGroup, e.documentId)), e);
  9136. i = i.insert(r.key, r), i.size === s && n.done();
  9137. })).next((() => i));
  9138. }
  9139. newChangeBuffer(t) {
  9140. return new lo(this, !!t && t.trackRemovals);
  9141. }
  9142. getSize(t) {
  9143. return this.getMetadata(t).next((t => t.byteSize));
  9144. }
  9145. getMetadata(t) {
  9146. return fo(t).get("remoteDocumentGlobalKey").next((t => (M(!!t), t)));
  9147. }
  9148. Qn(t, e) {
  9149. return fo(t).put("remoteDocumentGlobalKey", e);
  9150. }
  9151. /**
  9152. * Decodes `dbRemoteDoc` and returns the document (or an invalid document if
  9153. * the document corresponds to the format used for sentinel deletes).
  9154. */ jn(t, e) {
  9155. if (e) {
  9156. const t = Ji(this.yt, e);
  9157. // Whether the document is a sentinel removal and should only be used in the
  9158. // `getNewDocumentChanges()`
  9159. if (!(t.isNoDocument() && t.version.isEqual(st.min()))) return t;
  9160. }
  9161. return Ze.newInvalidDocument(t);
  9162. }
  9163. }
  9164. /** Creates a new IndexedDbRemoteDocumentCache. */ function ho(t) {
  9165. return new ao(t);
  9166. }
  9167. /**
  9168. * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.
  9169. *
  9170. * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size
  9171. * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb
  9172. * when we apply the changes.
  9173. */ class lo extends co {
  9174. /**
  9175. * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.
  9176. * @param trackRemovals - Whether to create sentinel deletes that can be tracked by
  9177. * `getNewDocumentChanges()`.
  9178. */
  9179. constructor(t, e) {
  9180. super(), this.Yn = t, this.trackRemovals = e,
  9181. // A map of document sizes and read times prior to applying the changes in
  9182. // this buffer.
  9183. this.Xn = new ls((t => t.toString()), ((t, e) => t.isEqual(e)));
  9184. }
  9185. applyChanges(t) {
  9186. const e = [];
  9187. let n = 0, s = new We(((t, e) => Z(t.canonicalString(), e.canonicalString())));
  9188. return this.changes.forEach(((i, r) => {
  9189. const o = this.Xn.get(i);
  9190. if (e.push(this.Yn.removeEntry(t, i, o.readTime)), r.isValidDocument()) {
  9191. const u = Yi(this.Yn.yt, r);
  9192. s = s.add(i.path.popLast());
  9193. const c = Qr(u);
  9194. n += c - o.size, e.push(this.Yn.addEntry(t, i, u));
  9195. } else if (n -= o.size, this.trackRemovals) {
  9196. // In order to track removals, we store a "sentinel delete" in the
  9197. // RemoteDocumentCache. This entry is represented by a NoDocument
  9198. // with a version of 0 and ignored by `maybeDecodeDocument()` but
  9199. // preserved in `getNewDocumentChanges()`.
  9200. const n = Yi(this.Yn.yt, r.convertToNoDocument(st.min()));
  9201. e.push(this.Yn.addEntry(t, i, n));
  9202. }
  9203. })), s.forEach((n => {
  9204. e.push(this.Yn.indexManager.addToCollectionParentIndex(t, n));
  9205. })), e.push(this.Yn.updateMetadata(t, n)), At.waitFor(e);
  9206. }
  9207. getFromCache(t, e) {
  9208. // Record the size of everything we load from the cache so we can compute a delta later.
  9209. return this.Yn.Wn(t, e).next((t => (this.Xn.set(e, {
  9210. size: t.size,
  9211. readTime: t.document.readTime
  9212. }), t.document)));
  9213. }
  9214. getAllFromCache(t, e) {
  9215. // Record the size of everything we load from the cache so we can compute
  9216. // a delta later.
  9217. return this.Yn.Hn(t, e).next((({documents: t, Jn: e}) => (
  9218. // Note: `getAllFromCache` returns two maps instead of a single map from
  9219. // keys to `DocumentSizeEntry`s. This is to allow returning the
  9220. // `MutableDocumentMap` directly, without a conversion.
  9221. e.forEach(((e, n) => {
  9222. this.Xn.set(e, {
  9223. size: n,
  9224. readTime: t.get(e).readTime
  9225. });
  9226. })), t)));
  9227. }
  9228. }
  9229. function fo(t) {
  9230. return Gi(t, "remoteDocumentGlobal");
  9231. }
  9232. /**
  9233. * Helper to get a typed SimpleDbStore for the remoteDocuments object store.
  9234. */ function _o(t) {
  9235. return Gi(t, "remoteDocumentsV14");
  9236. }
  9237. /**
  9238. * Returns a key that can be used for document lookups on the
  9239. * `DbRemoteDocumentDocumentKeyIndex` index.
  9240. */ function wo(t) {
  9241. const e = t.path.toArray();
  9242. return [
  9243. /* prefix path */ e.slice(0, e.length - 2),
  9244. /* collection id */ e[e.length - 2],
  9245. /* document id */ e[e.length - 1] ];
  9246. }
  9247. function mo(t, e) {
  9248. const n = e.documentKey.path.toArray();
  9249. return [
  9250. /* collection id */ t, Xi(e.readTime),
  9251. /* prefix path */ n.slice(0, n.length - 2),
  9252. /* document id */ n.length > 0 ? n[n.length - 1] : "" ];
  9253. }
  9254. /**
  9255. * Comparator that compares document keys according to the primary key sorting
  9256. * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id
  9257. * and then document ID).
  9258. *
  9259. * Visible for testing.
  9260. */ function go(t, e) {
  9261. const n = t.path.toArray(), s = e.path.toArray();
  9262. // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74
  9263. let i = 0;
  9264. for (let t = 0; t < n.length - 2 && t < s.length - 2; ++t) if (i = Z(n[t], s[t]),
  9265. i) return i;
  9266. return i = Z(n.length, s.length), i || (i = Z(n[n.length - 2], s[s.length - 2]),
  9267. i || Z(n[n.length - 1], s[s.length - 1]));
  9268. }
  9269. /**
  9270. * @license
  9271. * Copyright 2017 Google LLC
  9272. *
  9273. * Licensed under the Apache License, Version 2.0 (the "License");
  9274. * you may not use this file except in compliance with the License.
  9275. * You may obtain a copy of the License at
  9276. *
  9277. * http://www.apache.org/licenses/LICENSE-2.0
  9278. *
  9279. * Unless required by applicable law or agreed to in writing, software
  9280. * distributed under the License is distributed on an "AS IS" BASIS,
  9281. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9282. * See the License for the specific language governing permissions and
  9283. * limitations under the License.
  9284. */
  9285. /**
  9286. * Schema Version for the Web client:
  9287. * 1. Initial version including Mutation Queue, Query Cache, and Remote
  9288. * Document Cache
  9289. * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No
  9290. * longer required because migration 3 unconditionally clears it.
  9291. * 3. Dropped and re-created Query Cache to deal with cache corruption related
  9292. * to limbo resolution. Addresses
  9293. * https://github.com/firebase/firebase-ios-sdk/issues/1548
  9294. * 4. Multi-Tab Support.
  9295. * 5. Removal of held write acks.
  9296. * 6. Create document global for tracking document cache size.
  9297. * 7. Ensure every cached document has a sentinel row with a sequence number.
  9298. * 8. Add collection-parent index for Collection Group queries.
  9299. * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than
  9300. * an auto-incrementing ID. This is required for Index-Free queries.
  9301. * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.
  9302. * 11. Add bundles and named_queries for bundle support.
  9303. * 12. Add document overlays.
  9304. * 13. Rewrite the keys of the remote document cache to allow for efficient
  9305. * document lookup via `getAll()`.
  9306. * 14. Add overlays.
  9307. * 15. Add indexing support.
  9308. */
  9309. /**
  9310. * @license
  9311. * Copyright 2022 Google LLC
  9312. *
  9313. * Licensed under the Apache License, Version 2.0 (the "License");
  9314. * you may not use this file except in compliance with the License.
  9315. * You may obtain a copy of the License at
  9316. *
  9317. * http://www.apache.org/licenses/LICENSE-2.0
  9318. *
  9319. * Unless required by applicable law or agreed to in writing, software
  9320. * distributed under the License is distributed on an "AS IS" BASIS,
  9321. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9322. * See the License for the specific language governing permissions and
  9323. * limitations under the License.
  9324. */
  9325. /**
  9326. * Represents a local view (overlay) of a document, and the fields that are
  9327. * locally mutated.
  9328. */
  9329. class yo {
  9330. constructor(t,
  9331. /**
  9332. * The fields that are locally mutated by patch mutations.
  9333. *
  9334. * If the overlayed document is from set or delete mutations, this is `null`.
  9335. * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.
  9336. */
  9337. e) {
  9338. this.overlayedDocument = t, this.mutatedFields = e;
  9339. }
  9340. }
  9341. /**
  9342. * @license
  9343. * Copyright 2017 Google LLC
  9344. *
  9345. * Licensed under the Apache License, Version 2.0 (the "License");
  9346. * you may not use this file except in compliance with the License.
  9347. * You may obtain a copy of the License at
  9348. *
  9349. * http://www.apache.org/licenses/LICENSE-2.0
  9350. *
  9351. * Unless required by applicable law or agreed to in writing, software
  9352. * distributed under the License is distributed on an "AS IS" BASIS,
  9353. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9354. * See the License for the specific language governing permissions and
  9355. * limitations under the License.
  9356. */
  9357. /**
  9358. * A readonly view of the local state of all documents we're tracking (i.e. we
  9359. * have a cached version in remoteDocumentCache or local mutations for the
  9360. * document). The view is computed by applying the mutations in the
  9361. * MutationQueue to the RemoteDocumentCache.
  9362. */ class po {
  9363. constructor(t, e, n, s) {
  9364. this.remoteDocumentCache = t, this.mutationQueue = e, this.documentOverlayCache = n,
  9365. this.indexManager = s;
  9366. }
  9367. /**
  9368. * Get the local view of the document identified by `key`.
  9369. *
  9370. * @returns Local view of the document or null if we don't have any cached
  9371. * state for it.
  9372. */ getDocument(t, e) {
  9373. let n = null;
  9374. return this.documentOverlayCache.getOverlay(t, e).next((s => (n = s, this.remoteDocumentCache.getEntry(t, e)))).next((t => (null !== n && Jn(n.mutation, t, Je.empty(), nt.now()),
  9375. t)));
  9376. }
  9377. /**
  9378. * Gets the local view of the documents identified by `keys`.
  9379. *
  9380. * If we don't have cached state for a document in `keys`, a NoDocument will
  9381. * be stored for that key in the resulting set.
  9382. */ getDocuments(t, e) {
  9383. return this.remoteDocumentCache.getEntries(t, e).next((e => this.getLocalViewOfDocuments(t, e, Es()).next((() => e))));
  9384. }
  9385. /**
  9386. * Similar to `getDocuments`, but creates the local view from the given
  9387. * `baseDocs` without retrieving documents from the local store.
  9388. *
  9389. * @param transaction - The transaction this operation is scoped to.
  9390. * @param docs - The documents to apply local mutations to get the local views.
  9391. * @param existenceStateChanged - The set of document keys whose existence state
  9392. * is changed. This is useful to determine if some documents overlay needs
  9393. * to be recalculated.
  9394. */ getLocalViewOfDocuments(t, e, n = Es()) {
  9395. const s = gs();
  9396. return this.populateOverlays(t, s, e).next((() => this.computeViews(t, e, s, n).next((t => {
  9397. let e = ws();
  9398. return t.forEach(((t, n) => {
  9399. e = e.insert(t, n.overlayedDocument);
  9400. })), e;
  9401. }))));
  9402. }
  9403. /**
  9404. * Gets the overlayed documents for the given document map, which will include
  9405. * the local view of those documents and a `FieldMask` indicating which fields
  9406. * are mutated locally, `null` if overlay is a Set or Delete mutation.
  9407. */ getOverlayedDocuments(t, e) {
  9408. const n = gs();
  9409. return this.populateOverlays(t, n, e).next((() => this.computeViews(t, e, n, Es())));
  9410. }
  9411. /**
  9412. * Fetches the overlays for {@code docs} and adds them to provided overlay map
  9413. * if the map does not already contain an entry for the given document key.
  9414. */ populateOverlays(t, e, n) {
  9415. const s = [];
  9416. return n.forEach((t => {
  9417. e.has(t) || s.push(t);
  9418. })), this.documentOverlayCache.getOverlays(t, s).next((t => {
  9419. t.forEach(((t, n) => {
  9420. e.set(t, n);
  9421. }));
  9422. }));
  9423. }
  9424. /**
  9425. * Computes the local view for the given documents.
  9426. *
  9427. * @param docs - The documents to compute views for. It also has the base
  9428. * version of the documents.
  9429. * @param overlays - The overlays that need to be applied to the given base
  9430. * version of the documents.
  9431. * @param existenceStateChanged - A set of documents whose existence states
  9432. * might have changed. This is used to determine if we need to re-calculate
  9433. * overlays from mutation queues.
  9434. * @return A map represents the local documents view.
  9435. */ computeViews(t, e, n, s) {
  9436. let i = ds();
  9437. const r = ps(), o = ps();
  9438. return e.forEach(((t, e) => {
  9439. const o = n.get(e.key);
  9440. // Recalculate an overlay if the document's existence state changed due to
  9441. // a remote event *and* the overlay is a PatchMutation. This is because
  9442. // document existence state can change if some patch mutation's
  9443. // preconditions are met.
  9444. // NOTE: we recalculate when `overlay` is undefined as well, because there
  9445. // might be a patch mutation whose precondition does not match before the
  9446. // change (hence overlay is undefined), but would now match.
  9447. s.has(e.key) && (void 0 === o || o.mutation instanceof ts) ? i = i.insert(e.key, e) : void 0 !== o ? (r.set(e.key, o.mutation.getFieldMask()),
  9448. Jn(o.mutation, e, o.mutation.getFieldMask(), nt.now())) :
  9449. // no overlay exists
  9450. // Using EMPTY to indicate there is no overlay for the document.
  9451. r.set(e.key, Je.empty());
  9452. })), this.recalculateAndSaveOverlays(t, i).next((t => (t.forEach(((t, e) => r.set(t, e))),
  9453. e.forEach(((t, e) => {
  9454. var n;
  9455. return o.set(t, new yo(e, null !== (n = r.get(t)) && void 0 !== n ? n : null));
  9456. })), o)));
  9457. }
  9458. recalculateAndSaveOverlays(t, e) {
  9459. const n = ps();
  9460. // A reverse lookup map from batch id to the documents within that batch.
  9461. let s = new Ge(((t, e) => t - e)), i = Es();
  9462. return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(t, e).next((t => {
  9463. for (const i of t) i.keys().forEach((t => {
  9464. const r = e.get(t);
  9465. if (null === r) return;
  9466. let o = n.get(t) || Je.empty();
  9467. o = i.applyToLocalView(r, o), n.set(t, o);
  9468. const u = (s.get(i.batchId) || Es()).add(t);
  9469. s = s.insert(i.batchId, u);
  9470. }));
  9471. })).next((() => {
  9472. const r = [], o = s.getReverseIterator();
  9473. // Iterate in descending order of batch IDs, and skip documents that are
  9474. // already saved.
  9475. for (;o.hasNext(); ) {
  9476. const s = o.getNext(), u = s.key, c = s.value, a = ys();
  9477. c.forEach((t => {
  9478. if (!i.has(t)) {
  9479. const s = zn(e.get(t), n.get(t));
  9480. null !== s && a.set(t, s), i = i.add(t);
  9481. }
  9482. })), r.push(this.documentOverlayCache.saveOverlays(t, u, a));
  9483. }
  9484. return At.waitFor(r);
  9485. })).next((() => n));
  9486. }
  9487. /**
  9488. * Recalculates overlays by reading the documents from remote document cache
  9489. * first, and saves them after they are calculated.
  9490. */ recalculateAndSaveOverlaysForDocumentKeys(t, e) {
  9491. return this.remoteDocumentCache.getEntries(t, e).next((e => this.recalculateAndSaveOverlays(t, e)));
  9492. }
  9493. /**
  9494. * Performs a query against the local view of all documents.
  9495. *
  9496. * @param transaction - The persistence transaction.
  9497. * @param query - The query to match documents against.
  9498. * @param offset - Read time and key to start scanning by (exclusive).
  9499. */ getDocumentsMatchingQuery(t, e, n) {
  9500. /**
  9501. * Returns whether the query matches a single document by path (rather than a
  9502. * collection).
  9503. */
  9504. return function(t) {
  9505. return ct.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
  9506. }(e) ? this.getDocumentsMatchingDocumentQuery(t, e.path) : wn(e) ? this.getDocumentsMatchingCollectionGroupQuery(t, e, n) : this.getDocumentsMatchingCollectionQuery(t, e, n);
  9507. }
  9508. /**
  9509. * Given a collection group, returns the next documents that follow the provided offset, along
  9510. * with an updated batch ID.
  9511. *
  9512. * <p>The documents returned by this method are ordered by remote version from the provided
  9513. * offset. If there are no more remote documents after the provided offset, documents with
  9514. * mutations in order of batch id from the offset are returned. Since all documents in a batch are
  9515. * returned together, the total number of documents returned can exceed {@code count}.
  9516. *
  9517. * @param transaction
  9518. * @param collectionGroup The collection group for the documents.
  9519. * @param offset The offset to index into.
  9520. * @param count The number of documents to return
  9521. * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.
  9522. */ getNextDocuments(t, e, n, s) {
  9523. return this.remoteDocumentCache.getAllFromCollectionGroup(t, e, n, s).next((i => {
  9524. const r = s - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(t, e, n.largestBatchId, s - i.size) : At.resolve(gs());
  9525. // The callsite will use the largest batch ID together with the latest read time to create
  9526. // a new index offset. Since we only process batch IDs if all remote documents have been read,
  9527. // no overlay will increase the overall read time. This is why we only need to special case
  9528. // the batch id.
  9529. let o = -1, u = i;
  9530. return r.next((e => At.forEach(e, ((e, n) => (o < n.largestBatchId && (o = n.largestBatchId),
  9531. i.get(e) ? At.resolve() : this.remoteDocumentCache.getEntry(t, e).next((t => {
  9532. u = u.insert(e, t);
  9533. }))))).next((() => this.populateOverlays(t, e, i))).next((() => this.computeViews(t, u, e, Es()))).next((t => ({
  9534. batchId: o,
  9535. changes: ms(t)
  9536. })))));
  9537. }));
  9538. }
  9539. getDocumentsMatchingDocumentQuery(t, e) {
  9540. // Just do a simple document lookup.
  9541. return this.getDocument(t, new ct(e)).next((t => {
  9542. let e = ws();
  9543. return t.isFoundDocument() && (e = e.insert(t.key, t)), e;
  9544. }));
  9545. }
  9546. getDocumentsMatchingCollectionGroupQuery(t, e, n) {
  9547. const s = e.collectionGroup;
  9548. let i = ws();
  9549. return this.indexManager.getCollectionParents(t, s).next((r => At.forEach(r, (r => {
  9550. const o = function(t, e) {
  9551. return new an(e,
  9552. /*collectionGroup=*/ null, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  9553. }(e, r.child(s));
  9554. return this.getDocumentsMatchingCollectionQuery(t, o, n).next((t => {
  9555. t.forEach(((t, e) => {
  9556. i = i.insert(t, e);
  9557. }));
  9558. }));
  9559. })).next((() => i))));
  9560. }
  9561. getDocumentsMatchingCollectionQuery(t, e, n) {
  9562. // Query the remote documents and overlay mutations.
  9563. let s;
  9564. return this.remoteDocumentCache.getAllFromCollection(t, e.path, n).next((i => (s = i,
  9565. this.documentOverlayCache.getOverlaysForCollection(t, e.path, n.largestBatchId)))).next((t => {
  9566. // As documents might match the query because of their overlay we need to
  9567. // include documents for all overlays in the initial document set.
  9568. t.forEach(((t, e) => {
  9569. const n = e.getKey();
  9570. null === s.get(n) && (s = s.insert(n, Ze.newInvalidDocument(n)));
  9571. }));
  9572. // Apply the overlays and match against the query.
  9573. let n = ws();
  9574. return s.forEach(((s, i) => {
  9575. const r = t.get(s);
  9576. void 0 !== r && Jn(r.mutation, i, Je.empty(), nt.now()),
  9577. // Finally, insert the documents that still match the query
  9578. An(e, i) && (n = n.insert(s, i));
  9579. })), n;
  9580. }));
  9581. }
  9582. }
  9583. /**
  9584. * @license
  9585. * Copyright 2020 Google LLC
  9586. *
  9587. * Licensed under the Apache License, Version 2.0 (the "License");
  9588. * you may not use this file except in compliance with the License.
  9589. * You may obtain a copy of the License at
  9590. *
  9591. * http://www.apache.org/licenses/LICENSE-2.0
  9592. *
  9593. * Unless required by applicable law or agreed to in writing, software
  9594. * distributed under the License is distributed on an "AS IS" BASIS,
  9595. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9596. * See the License for the specific language governing permissions and
  9597. * limitations under the License.
  9598. */ class Io {
  9599. constructor(t) {
  9600. this.yt = t, this.Zn = new Map, this.ts = new Map;
  9601. }
  9602. getBundleMetadata(t, e) {
  9603. return At.resolve(this.Zn.get(e));
  9604. }
  9605. saveBundleMetadata(t, e) {
  9606. /** Decodes a BundleMetadata proto into a BundleMetadata object. */
  9607. var n;
  9608. return this.Zn.set(e.id, {
  9609. id: (n = e).id,
  9610. version: n.version,
  9611. createTime: qs(n.createTime)
  9612. }), At.resolve();
  9613. }
  9614. getNamedQuery(t, e) {
  9615. return At.resolve(this.ts.get(e));
  9616. }
  9617. saveNamedQuery(t, e) {
  9618. return this.ts.set(e.name, function(t) {
  9619. return {
  9620. name: t.name,
  9621. query: ir(t.bundledQuery),
  9622. readTime: qs(t.readTime)
  9623. };
  9624. }(e)), At.resolve();
  9625. }
  9626. }
  9627. /**
  9628. * @license
  9629. * Copyright 2022 Google LLC
  9630. *
  9631. * Licensed under the Apache License, Version 2.0 (the "License");
  9632. * you may not use this file except in compliance with the License.
  9633. * You may obtain a copy of the License at
  9634. *
  9635. * http://www.apache.org/licenses/LICENSE-2.0
  9636. *
  9637. * Unless required by applicable law or agreed to in writing, software
  9638. * distributed under the License is distributed on an "AS IS" BASIS,
  9639. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9640. * See the License for the specific language governing permissions and
  9641. * limitations under the License.
  9642. */
  9643. /**
  9644. * An in-memory implementation of DocumentOverlayCache.
  9645. */ class To {
  9646. constructor() {
  9647. // A map sorted by DocumentKey, whose value is a pair of the largest batch id
  9648. // for the overlay and the overlay itself.
  9649. this.overlays = new Ge(ct.comparator), this.es = new Map;
  9650. }
  9651. getOverlay(t, e) {
  9652. return At.resolve(this.overlays.get(e));
  9653. }
  9654. getOverlays(t, e) {
  9655. const n = gs();
  9656. return At.forEach(e, (e => this.getOverlay(t, e).next((t => {
  9657. null !== t && n.set(e, t);
  9658. })))).next((() => n));
  9659. }
  9660. saveOverlays(t, e, n) {
  9661. return n.forEach(((n, s) => {
  9662. this.oe(t, e, s);
  9663. })), At.resolve();
  9664. }
  9665. removeOverlaysForBatchId(t, e, n) {
  9666. const s = this.es.get(n);
  9667. return void 0 !== s && (s.forEach((t => this.overlays = this.overlays.remove(t))),
  9668. this.es.delete(n)), At.resolve();
  9669. }
  9670. getOverlaysForCollection(t, e, n) {
  9671. const s = gs(), i = e.length + 1, r = new ct(e.child("")), o = this.overlays.getIteratorFrom(r);
  9672. for (;o.hasNext(); ) {
  9673. const t = o.getNext().value, r = t.getKey();
  9674. if (!e.isPrefixOf(r.path)) break;
  9675. // Documents from sub-collections
  9676. r.path.length === i && (t.largestBatchId > n && s.set(t.getKey(), t));
  9677. }
  9678. return At.resolve(s);
  9679. }
  9680. getOverlaysForCollectionGroup(t, e, n, s) {
  9681. let i = new Ge(((t, e) => t - e));
  9682. const r = this.overlays.getIterator();
  9683. for (;r.hasNext(); ) {
  9684. const t = r.getNext().value;
  9685. if (t.getKey().getCollectionGroup() === e && t.largestBatchId > n) {
  9686. let e = i.get(t.largestBatchId);
  9687. null === e && (e = gs(), i = i.insert(t.largestBatchId, e)), e.set(t.getKey(), t);
  9688. }
  9689. }
  9690. const o = gs(), u = i.getIterator();
  9691. for (;u.hasNext(); ) {
  9692. if (u.getNext().value.forEach(((t, e) => o.set(t, e))), o.size() >= s) break;
  9693. }
  9694. return At.resolve(o);
  9695. }
  9696. oe(t, e, n) {
  9697. // Remove the association of the overlay to its batch id.
  9698. const s = this.overlays.get(n.key);
  9699. if (null !== s) {
  9700. const t = this.es.get(s.largestBatchId).delete(n.key);
  9701. this.es.set(s.largestBatchId, t);
  9702. }
  9703. this.overlays = this.overlays.insert(n.key, new Wi(e, n));
  9704. // Create the association of this overlay to the given largestBatchId.
  9705. let i = this.es.get(e);
  9706. void 0 === i && (i = Es(), this.es.set(e, i)), this.es.set(e, i.add(n.key));
  9707. }
  9708. }
  9709. /**
  9710. * @license
  9711. * Copyright 2017 Google LLC
  9712. *
  9713. * Licensed under the Apache License, Version 2.0 (the "License");
  9714. * you may not use this file except in compliance with the License.
  9715. * You may obtain a copy of the License at
  9716. *
  9717. * http://www.apache.org/licenses/LICENSE-2.0
  9718. *
  9719. * Unless required by applicable law or agreed to in writing, software
  9720. * distributed under the License is distributed on an "AS IS" BASIS,
  9721. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9722. * See the License for the specific language governing permissions and
  9723. * limitations under the License.
  9724. */
  9725. /**
  9726. * A collection of references to a document from some kind of numbered entity
  9727. * (either a target ID or batch ID). As references are added to or removed from
  9728. * the set corresponding events are emitted to a registered garbage collector.
  9729. *
  9730. * Each reference is represented by a DocumentReference object. Each of them
  9731. * contains enough information to uniquely identify the reference. They are all
  9732. * stored primarily in a set sorted by key. A document is considered garbage if
  9733. * there's no references in that set (this can be efficiently checked thanks to
  9734. * sorting by key).
  9735. *
  9736. * ReferenceSet also keeps a secondary set that contains references sorted by
  9737. * IDs. This one is used to efficiently implement removal of all references by
  9738. * some target ID.
  9739. */ class Eo {
  9740. constructor() {
  9741. // A set of outstanding references to a document sorted by key.
  9742. this.ns = new We(Ao.ss),
  9743. // A set of outstanding references to a document sorted by target id.
  9744. this.rs = new We(Ao.os);
  9745. }
  9746. /** Returns true if the reference set contains no references. */ isEmpty() {
  9747. return this.ns.isEmpty();
  9748. }
  9749. /** Adds a reference to the given document key for the given ID. */ addReference(t, e) {
  9750. const n = new Ao(t, e);
  9751. this.ns = this.ns.add(n), this.rs = this.rs.add(n);
  9752. }
  9753. /** Add references to the given document keys for the given ID. */ us(t, e) {
  9754. t.forEach((t => this.addReference(t, e)));
  9755. }
  9756. /**
  9757. * Removes a reference to the given document key for the given
  9758. * ID.
  9759. */ removeReference(t, e) {
  9760. this.cs(new Ao(t, e));
  9761. }
  9762. hs(t, e) {
  9763. t.forEach((t => this.removeReference(t, e)));
  9764. }
  9765. /**
  9766. * Clears all references with a given ID. Calls removeRef() for each key
  9767. * removed.
  9768. */ ls(t) {
  9769. const e = new ct(new rt([])), n = new Ao(e, t), s = new Ao(e, t + 1), i = [];
  9770. return this.rs.forEachInRange([ n, s ], (t => {
  9771. this.cs(t), i.push(t.key);
  9772. })), i;
  9773. }
  9774. fs() {
  9775. this.ns.forEach((t => this.cs(t)));
  9776. }
  9777. cs(t) {
  9778. this.ns = this.ns.delete(t), this.rs = this.rs.delete(t);
  9779. }
  9780. ds(t) {
  9781. const e = new ct(new rt([])), n = new Ao(e, t), s = new Ao(e, t + 1);
  9782. let i = Es();
  9783. return this.rs.forEachInRange([ n, s ], (t => {
  9784. i = i.add(t.key);
  9785. })), i;
  9786. }
  9787. containsKey(t) {
  9788. const e = new Ao(t, 0), n = this.ns.firstAfterOrEqual(e);
  9789. return null !== n && t.isEqual(n.key);
  9790. }
  9791. }
  9792. class Ao {
  9793. constructor(t, e) {
  9794. this.key = t, this._s = e;
  9795. }
  9796. /** Compare by key then by ID */ static ss(t, e) {
  9797. return ct.comparator(t.key, e.key) || Z(t._s, e._s);
  9798. }
  9799. /** Compare by ID then by key */ static os(t, e) {
  9800. return Z(t._s, e._s) || ct.comparator(t.key, e.key);
  9801. }
  9802. }
  9803. /**
  9804. * @license
  9805. * Copyright 2017 Google LLC
  9806. *
  9807. * Licensed under the Apache License, Version 2.0 (the "License");
  9808. * you may not use this file except in compliance with the License.
  9809. * You may obtain a copy of the License at
  9810. *
  9811. * http://www.apache.org/licenses/LICENSE-2.0
  9812. *
  9813. * Unless required by applicable law or agreed to in writing, software
  9814. * distributed under the License is distributed on an "AS IS" BASIS,
  9815. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9816. * See the License for the specific language governing permissions and
  9817. * limitations under the License.
  9818. */ class Ro {
  9819. constructor(t, e) {
  9820. this.indexManager = t, this.referenceDelegate = e,
  9821. /**
  9822. * The set of all mutations that have been sent but not yet been applied to
  9823. * the backend.
  9824. */
  9825. this.mutationQueue = [],
  9826. /** Next value to use when assigning sequential IDs to each mutation batch. */
  9827. this.ws = 1,
  9828. /** An ordered mapping between documents and the mutations batch IDs. */
  9829. this.gs = new We(Ao.ss);
  9830. }
  9831. checkEmpty(t) {
  9832. return At.resolve(0 === this.mutationQueue.length);
  9833. }
  9834. addMutationBatch(t, e, n, s) {
  9835. const i = this.ws;
  9836. this.ws++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];
  9837. const r = new Qi(i, e, n, s);
  9838. this.mutationQueue.push(r);
  9839. // Track references by document key and index collection parents.
  9840. for (const e of s) this.gs = this.gs.add(new Ao(e.key, i)), this.indexManager.addToCollectionParentIndex(t, e.key.path.popLast());
  9841. return At.resolve(r);
  9842. }
  9843. lookupMutationBatch(t, e) {
  9844. return At.resolve(this.ys(e));
  9845. }
  9846. getNextMutationBatchAfterBatchId(t, e) {
  9847. const n = e + 1, s = this.ps(n), i = s < 0 ? 0 : s;
  9848. // The requested batchId may still be out of range so normalize it to the
  9849. // start of the queue.
  9850. return At.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);
  9851. }
  9852. getHighestUnacknowledgedBatchId() {
  9853. return At.resolve(0 === this.mutationQueue.length ? -1 : this.ws - 1);
  9854. }
  9855. getAllMutationBatches(t) {
  9856. return At.resolve(this.mutationQueue.slice());
  9857. }
  9858. getAllMutationBatchesAffectingDocumentKey(t, e) {
  9859. const n = new Ao(e, 0), s = new Ao(e, Number.POSITIVE_INFINITY), i = [];
  9860. return this.gs.forEachInRange([ n, s ], (t => {
  9861. const e = this.ys(t._s);
  9862. i.push(e);
  9863. })), At.resolve(i);
  9864. }
  9865. getAllMutationBatchesAffectingDocumentKeys(t, e) {
  9866. let n = new We(Z);
  9867. return e.forEach((t => {
  9868. const e = new Ao(t, 0), s = new Ao(t, Number.POSITIVE_INFINITY);
  9869. this.gs.forEachInRange([ e, s ], (t => {
  9870. n = n.add(t._s);
  9871. }));
  9872. })), At.resolve(this.Is(n));
  9873. }
  9874. getAllMutationBatchesAffectingQuery(t, e) {
  9875. // Use the query path as a prefix for testing if a document matches the
  9876. // query.
  9877. const n = e.path, s = n.length + 1;
  9878. // Construct a document reference for actually scanning the index. Unlike
  9879. // the prefix the document key in this reference must have an even number of
  9880. // segments. The empty segment can be used a suffix of the query path
  9881. // because it precedes all other segments in an ordered traversal.
  9882. let i = n;
  9883. ct.isDocumentKey(i) || (i = i.child(""));
  9884. const r = new Ao(new ct(i), 0);
  9885. // Find unique batchIDs referenced by all documents potentially matching the
  9886. // query.
  9887. let o = new We(Z);
  9888. return this.gs.forEachWhile((t => {
  9889. const e = t.key.path;
  9890. return !!n.isPrefixOf(e) && (
  9891. // Rows with document keys more than one segment longer than the query
  9892. // path can't be matches. For example, a query on 'rooms' can't match
  9893. // the document /rooms/abc/messages/xyx.
  9894. // TODO(mcg): we'll need a different scanner when we implement
  9895. // ancestor queries.
  9896. e.length === s && (o = o.add(t._s)), !0);
  9897. }), r), At.resolve(this.Is(o));
  9898. }
  9899. Is(t) {
  9900. // Construct an array of matching batches, sorted by batchID to ensure that
  9901. // multiple mutations affecting the same document key are applied in order.
  9902. const e = [];
  9903. return t.forEach((t => {
  9904. const n = this.ys(t);
  9905. null !== n && e.push(n);
  9906. })), e;
  9907. }
  9908. removeMutationBatch(t, e) {
  9909. M(0 === this.Ts(e.batchId, "removed")), this.mutationQueue.shift();
  9910. let n = this.gs;
  9911. return At.forEach(e.mutations, (s => {
  9912. const i = new Ao(s.key, e.batchId);
  9913. return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(t, s.key);
  9914. })).next((() => {
  9915. this.gs = n;
  9916. }));
  9917. }
  9918. An(t) {
  9919. // No-op since the memory mutation queue does not maintain a separate cache.
  9920. }
  9921. containsKey(t, e) {
  9922. const n = new Ao(e, 0), s = this.gs.firstAfterOrEqual(n);
  9923. return At.resolve(e.isEqual(s && s.key));
  9924. }
  9925. performConsistencyCheck(t) {
  9926. return this.mutationQueue.length, At.resolve();
  9927. }
  9928. /**
  9929. * Finds the index of the given batchId in the mutation queue and asserts that
  9930. * the resulting index is within the bounds of the queue.
  9931. *
  9932. * @param batchId - The batchId to search for
  9933. * @param action - A description of what the caller is doing, phrased in passive
  9934. * form (e.g. "acknowledged" in a routine that acknowledges batches).
  9935. */ Ts(t, e) {
  9936. return this.ps(t);
  9937. }
  9938. /**
  9939. * Finds the index of the given batchId in the mutation queue. This operation
  9940. * is O(1).
  9941. *
  9942. * @returns The computed index of the batch with the given batchId, based on
  9943. * the state of the queue. Note this index can be negative if the requested
  9944. * batchId has already been remvoed from the queue or past the end of the
  9945. * queue if the batchId is larger than the last added batch.
  9946. */ ps(t) {
  9947. if (0 === this.mutationQueue.length)
  9948. // As an index this is past the end of the queue
  9949. return 0;
  9950. // Examine the front of the queue to figure out the difference between the
  9951. // batchId and indexes in the array. Note that since the queue is ordered
  9952. // by batchId, if the first batch has a larger batchId then the requested
  9953. // batchId doesn't exist in the queue.
  9954. return t - this.mutationQueue[0].batchId;
  9955. }
  9956. /**
  9957. * A version of lookupMutationBatch that doesn't return a promise, this makes
  9958. * other functions that uses this code easier to read and more efficent.
  9959. */ ys(t) {
  9960. const e = this.ps(t);
  9961. if (e < 0 || e >= this.mutationQueue.length) return null;
  9962. return this.mutationQueue[e];
  9963. }
  9964. }
  9965. /**
  9966. * @license
  9967. * Copyright 2017 Google LLC
  9968. *
  9969. * Licensed under the Apache License, Version 2.0 (the "License");
  9970. * you may not use this file except in compliance with the License.
  9971. * You may obtain a copy of the License at
  9972. *
  9973. * http://www.apache.org/licenses/LICENSE-2.0
  9974. *
  9975. * Unless required by applicable law or agreed to in writing, software
  9976. * distributed under the License is distributed on an "AS IS" BASIS,
  9977. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9978. * See the License for the specific language governing permissions and
  9979. * limitations under the License.
  9980. */
  9981. /**
  9982. * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke
  9983. * `newMemoryRemoteDocumentCache()`.
  9984. */
  9985. class bo {
  9986. /**
  9987. * @param sizer - Used to assess the size of a document. For eager GC, this is
  9988. * expected to just return 0 to avoid unnecessarily doing the work of
  9989. * calculating the size.
  9990. */
  9991. constructor(t) {
  9992. this.Es = t,
  9993. /** Underlying cache of documents and their read times. */
  9994. this.docs = new Ge(ct.comparator),
  9995. /** Size of all cached documents. */
  9996. this.size = 0;
  9997. }
  9998. setIndexManager(t) {
  9999. this.indexManager = t;
  10000. }
  10001. /**
  10002. * Adds the supplied entry to the cache and updates the cache size as appropriate.
  10003. *
  10004. * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
  10005. * returned by `newChangeBuffer()`.
  10006. */ addEntry(t, e) {
  10007. const n = e.key, s = this.docs.get(n), i = s ? s.size : 0, r = this.Es(e);
  10008. return this.docs = this.docs.insert(n, {
  10009. document: e.mutableCopy(),
  10010. size: r
  10011. }), this.size += r - i, this.indexManager.addToCollectionParentIndex(t, n.path.popLast());
  10012. }
  10013. /**
  10014. * Removes the specified entry from the cache and updates the cache size as appropriate.
  10015. *
  10016. * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
  10017. * returned by `newChangeBuffer()`.
  10018. */ removeEntry(t) {
  10019. const e = this.docs.get(t);
  10020. e && (this.docs = this.docs.remove(t), this.size -= e.size);
  10021. }
  10022. getEntry(t, e) {
  10023. const n = this.docs.get(e);
  10024. return At.resolve(n ? n.document.mutableCopy() : Ze.newInvalidDocument(e));
  10025. }
  10026. getEntries(t, e) {
  10027. let n = ds();
  10028. return e.forEach((t => {
  10029. const e = this.docs.get(t);
  10030. n = n.insert(t, e ? e.document.mutableCopy() : Ze.newInvalidDocument(t));
  10031. })), At.resolve(n);
  10032. }
  10033. getAllFromCollection(t, e, n) {
  10034. let s = ds();
  10035. // Documents are ordered by key, so we can use a prefix scan to narrow down
  10036. // the documents we need to match the query against.
  10037. const i = new ct(e.child("")), r = this.docs.getIteratorFrom(i);
  10038. for (;r.hasNext(); ) {
  10039. const {key: t, value: {document: i}} = r.getNext();
  10040. if (!e.isPrefixOf(t.path)) break;
  10041. t.path.length > e.length + 1 || (pt(gt(i), n) <= 0 || (s = s.insert(i.key, i.mutableCopy())));
  10042. }
  10043. return At.resolve(s);
  10044. }
  10045. getAllFromCollectionGroup(t, e, n, s) {
  10046. // This method should only be called from the IndexBackfiller if persistence
  10047. // is enabled.
  10048. O();
  10049. }
  10050. As(t, e) {
  10051. return At.forEach(this.docs, (t => e(t)));
  10052. }
  10053. newChangeBuffer(t) {
  10054. // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps
  10055. // a separate changelog and does not need special handling for removals.
  10056. return new Po(this);
  10057. }
  10058. getSize(t) {
  10059. return At.resolve(this.size);
  10060. }
  10061. }
  10062. /**
  10063. * Creates a new memory-only RemoteDocumentCache.
  10064. *
  10065. * @param sizer - Used to assess the size of a document. For eager GC, this is
  10066. * expected to just return 0 to avoid unnecessarily doing the work of
  10067. * calculating the size.
  10068. */
  10069. /**
  10070. * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.
  10071. */
  10072. class Po extends co {
  10073. constructor(t) {
  10074. super(), this.Yn = t;
  10075. }
  10076. applyChanges(t) {
  10077. const e = [];
  10078. return this.changes.forEach(((n, s) => {
  10079. s.isValidDocument() ? e.push(this.Yn.addEntry(t, s)) : this.Yn.removeEntry(n);
  10080. })), At.waitFor(e);
  10081. }
  10082. getFromCache(t, e) {
  10083. return this.Yn.getEntry(t, e);
  10084. }
  10085. getAllFromCache(t, e) {
  10086. return this.Yn.getEntries(t, e);
  10087. }
  10088. }
  10089. /**
  10090. * @license
  10091. * Copyright 2017 Google LLC
  10092. *
  10093. * Licensed under the Apache License, Version 2.0 (the "License");
  10094. * you may not use this file except in compliance with the License.
  10095. * You may obtain a copy of the License at
  10096. *
  10097. * http://www.apache.org/licenses/LICENSE-2.0
  10098. *
  10099. * Unless required by applicable law or agreed to in writing, software
  10100. * distributed under the License is distributed on an "AS IS" BASIS,
  10101. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10102. * See the License for the specific language governing permissions and
  10103. * limitations under the License.
  10104. */ class vo {
  10105. constructor(t) {
  10106. this.persistence = t,
  10107. /**
  10108. * Maps a target to the data about that target
  10109. */
  10110. this.Rs = new ls((t => nn(t)), sn),
  10111. /** The last received snapshot version. */
  10112. this.lastRemoteSnapshotVersion = st.min(),
  10113. /** The highest numbered target ID encountered. */
  10114. this.highestTargetId = 0,
  10115. /** The highest sequence number encountered. */
  10116. this.bs = 0,
  10117. /**
  10118. * A ordered bidirectional mapping between documents and the remote target
  10119. * IDs.
  10120. */
  10121. this.Ps = new Eo, this.targetCount = 0, this.vs = Yr.Pn();
  10122. }
  10123. forEachTarget(t, e) {
  10124. return this.Rs.forEach(((t, n) => e(n))), At.resolve();
  10125. }
  10126. getLastRemoteSnapshotVersion(t) {
  10127. return At.resolve(this.lastRemoteSnapshotVersion);
  10128. }
  10129. getHighestSequenceNumber(t) {
  10130. return At.resolve(this.bs);
  10131. }
  10132. allocateTargetId(t) {
  10133. return this.highestTargetId = this.vs.next(), At.resolve(this.highestTargetId);
  10134. }
  10135. setTargetsMetadata(t, e, n) {
  10136. return n && (this.lastRemoteSnapshotVersion = n), e > this.bs && (this.bs = e),
  10137. At.resolve();
  10138. }
  10139. Dn(t) {
  10140. this.Rs.set(t.target, t);
  10141. const e = t.targetId;
  10142. e > this.highestTargetId && (this.vs = new Yr(e), this.highestTargetId = e), t.sequenceNumber > this.bs && (this.bs = t.sequenceNumber);
  10143. }
  10144. addTargetData(t, e) {
  10145. return this.Dn(e), this.targetCount += 1, At.resolve();
  10146. }
  10147. updateTargetData(t, e) {
  10148. return this.Dn(e), At.resolve();
  10149. }
  10150. removeTargetData(t, e) {
  10151. return this.Rs.delete(e.target), this.Ps.ls(e.targetId), this.targetCount -= 1,
  10152. At.resolve();
  10153. }
  10154. removeTargets(t, e, n) {
  10155. let s = 0;
  10156. const i = [];
  10157. return this.Rs.forEach(((r, o) => {
  10158. o.sequenceNumber <= e && null === n.get(o.targetId) && (this.Rs.delete(r), i.push(this.removeMatchingKeysForTargetId(t, o.targetId)),
  10159. s++);
  10160. })), At.waitFor(i).next((() => s));
  10161. }
  10162. getTargetCount(t) {
  10163. return At.resolve(this.targetCount);
  10164. }
  10165. getTargetData(t, e) {
  10166. const n = this.Rs.get(e) || null;
  10167. return At.resolve(n);
  10168. }
  10169. addMatchingKeys(t, e, n) {
  10170. return this.Ps.us(e, n), At.resolve();
  10171. }
  10172. removeMatchingKeys(t, e, n) {
  10173. this.Ps.hs(e, n);
  10174. const s = this.persistence.referenceDelegate, i = [];
  10175. return s && e.forEach((e => {
  10176. i.push(s.markPotentiallyOrphaned(t, e));
  10177. })), At.waitFor(i);
  10178. }
  10179. removeMatchingKeysForTargetId(t, e) {
  10180. return this.Ps.ls(e), At.resolve();
  10181. }
  10182. getMatchingKeysForTargetId(t, e) {
  10183. const n = this.Ps.ds(e);
  10184. return At.resolve(n);
  10185. }
  10186. containsKey(t, e) {
  10187. return At.resolve(this.Ps.containsKey(e));
  10188. }
  10189. }
  10190. /**
  10191. * @license
  10192. * Copyright 2017 Google LLC
  10193. *
  10194. * Licensed under the Apache License, Version 2.0 (the "License");
  10195. * you may not use this file except in compliance with the License.
  10196. * You may obtain a copy of the License at
  10197. *
  10198. * http://www.apache.org/licenses/LICENSE-2.0
  10199. *
  10200. * Unless required by applicable law or agreed to in writing, software
  10201. * distributed under the License is distributed on an "AS IS" BASIS,
  10202. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10203. * See the License for the specific language governing permissions and
  10204. * limitations under the License.
  10205. */
  10206. /**
  10207. * A memory-backed instance of Persistence. Data is stored only in RAM and
  10208. * not persisted across sessions.
  10209. */
  10210. class Vo {
  10211. /**
  10212. * The constructor accepts a factory for creating a reference delegate. This
  10213. * allows both the delegate and this instance to have strong references to
  10214. * each other without having nullable fields that would then need to be
  10215. * checked or asserted on every access.
  10216. */
  10217. constructor(t, e) {
  10218. this.Vs = {}, this.overlays = {}, this.Ss = new Ot(0), this.Ds = !1, this.Ds = !0,
  10219. this.referenceDelegate = t(this), this.Cs = new vo(this);
  10220. this.indexManager = new Nr, this.remoteDocumentCache = function(t) {
  10221. return new bo(t);
  10222. }((t => this.referenceDelegate.xs(t))), this.yt = new Hi(e), this.Ns = new Io(this.yt);
  10223. }
  10224. start() {
  10225. return Promise.resolve();
  10226. }
  10227. shutdown() {
  10228. // No durable state to ensure is closed on shutdown.
  10229. return this.Ds = !1, Promise.resolve();
  10230. }
  10231. get started() {
  10232. return this.Ds;
  10233. }
  10234. setDatabaseDeletedListener() {
  10235. // No op.
  10236. }
  10237. setNetworkEnabled() {
  10238. // No op.
  10239. }
  10240. getIndexManager(t) {
  10241. // We do not currently support indices for memory persistence, so we can
  10242. // return the same shared instance of the memory index manager.
  10243. return this.indexManager;
  10244. }
  10245. getDocumentOverlayCache(t) {
  10246. let e = this.overlays[t.toKey()];
  10247. return e || (e = new To, this.overlays[t.toKey()] = e), e;
  10248. }
  10249. getMutationQueue(t, e) {
  10250. let n = this.Vs[t.toKey()];
  10251. return n || (n = new Ro(e, this.referenceDelegate), this.Vs[t.toKey()] = n), n;
  10252. }
  10253. getTargetCache() {
  10254. return this.Cs;
  10255. }
  10256. getRemoteDocumentCache() {
  10257. return this.remoteDocumentCache;
  10258. }
  10259. getBundleCache() {
  10260. return this.Ns;
  10261. }
  10262. runTransaction(t, e, n) {
  10263. C("MemoryPersistence", "Starting transaction:", t);
  10264. const s = new So(this.Ss.next());
  10265. return this.referenceDelegate.ks(), n(s).next((t => this.referenceDelegate.Os(s).next((() => t)))).toPromise().then((t => (s.raiseOnCommittedEvent(),
  10266. t)));
  10267. }
  10268. Ms(t, e) {
  10269. return At.or(Object.values(this.Vs).map((n => () => n.containsKey(t, e))));
  10270. }
  10271. }
  10272. /**
  10273. * Memory persistence is not actually transactional, but future implementations
  10274. * may have transaction-scoped state.
  10275. */ class So extends Tt {
  10276. constructor(t) {
  10277. super(), this.currentSequenceNumber = t;
  10278. }
  10279. }
  10280. class Do {
  10281. constructor(t) {
  10282. this.persistence = t,
  10283. /** Tracks all documents that are active in Query views. */
  10284. this.Fs = new Eo,
  10285. /** The list of documents that are potentially GCed after each transaction. */
  10286. this.$s = null;
  10287. }
  10288. static Bs(t) {
  10289. return new Do(t);
  10290. }
  10291. get Ls() {
  10292. if (this.$s) return this.$s;
  10293. throw O();
  10294. }
  10295. addReference(t, e, n) {
  10296. return this.Fs.addReference(n, e), this.Ls.delete(n.toString()), At.resolve();
  10297. }
  10298. removeReference(t, e, n) {
  10299. return this.Fs.removeReference(n, e), this.Ls.add(n.toString()), At.resolve();
  10300. }
  10301. markPotentiallyOrphaned(t, e) {
  10302. return this.Ls.add(e.toString()), At.resolve();
  10303. }
  10304. removeTarget(t, e) {
  10305. this.Fs.ls(e.targetId).forEach((t => this.Ls.add(t.toString())));
  10306. const n = this.persistence.getTargetCache();
  10307. return n.getMatchingKeysForTargetId(t, e.targetId).next((t => {
  10308. t.forEach((t => this.Ls.add(t.toString())));
  10309. })).next((() => n.removeTargetData(t, e)));
  10310. }
  10311. ks() {
  10312. this.$s = new Set;
  10313. }
  10314. Os(t) {
  10315. // Remove newly orphaned documents.
  10316. const e = this.persistence.getRemoteDocumentCache().newChangeBuffer();
  10317. return At.forEach(this.Ls, (n => {
  10318. const s = ct.fromPath(n);
  10319. return this.qs(t, s).next((t => {
  10320. t || e.removeEntry(s, st.min());
  10321. }));
  10322. })).next((() => (this.$s = null, e.apply(t))));
  10323. }
  10324. updateLimboDocument(t, e) {
  10325. return this.qs(t, e).next((t => {
  10326. t ? this.Ls.delete(e.toString()) : this.Ls.add(e.toString());
  10327. }));
  10328. }
  10329. xs(t) {
  10330. // For eager GC, we don't care about the document size, there are no size thresholds.
  10331. return 0;
  10332. }
  10333. qs(t, e) {
  10334. return At.or([ () => At.resolve(this.Fs.containsKey(e)), () => this.persistence.getTargetCache().containsKey(t, e), () => this.persistence.Ms(t, e) ]);
  10335. }
  10336. }
  10337. /**
  10338. * @license
  10339. * Copyright 2020 Google LLC
  10340. *
  10341. * Licensed under the Apache License, Version 2.0 (the "License");
  10342. * you may not use this file except in compliance with the License.
  10343. * You may obtain a copy of the License at
  10344. *
  10345. * http://www.apache.org/licenses/LICENSE-2.0
  10346. *
  10347. * Unless required by applicable law or agreed to in writing, software
  10348. * distributed under the License is distributed on an "AS IS" BASIS,
  10349. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10350. * See the License for the specific language governing permissions and
  10351. * limitations under the License.
  10352. */
  10353. /** Performs database creation and schema upgrades. */ class Co {
  10354. constructor(t) {
  10355. this.yt = t;
  10356. }
  10357. /**
  10358. * Performs database creation and schema upgrades.
  10359. *
  10360. * Note that in production, this method is only ever used to upgrade the schema
  10361. * to SCHEMA_VERSION. Different values of toVersion are only used for testing
  10362. * and local feature development.
  10363. */ $(t, e, n, s) {
  10364. const i = new Rt("createOrUpgrade", e);
  10365. n < 1 && s >= 1 && (function(t) {
  10366. t.createObjectStore("owner");
  10367. }(t), function(t) {
  10368. t.createObjectStore("mutationQueues", {
  10369. keyPath: "userId"
  10370. });
  10371. t.createObjectStore("mutations", {
  10372. keyPath: "batchId",
  10373. autoIncrement: !0
  10374. }).createIndex("userMutationsIndex", Ii, {
  10375. unique: !0
  10376. }), t.createObjectStore("documentMutations");
  10377. }
  10378. /**
  10379. * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads
  10380. * and rewrites all data.
  10381. */ (t), xo(t), function(t) {
  10382. t.createObjectStore("remoteDocuments");
  10383. }(t));
  10384. // Migration 2 to populate the targetGlobal object no longer needed since
  10385. // migration 3 unconditionally clears it.
  10386. let r = At.resolve();
  10387. return n < 3 && s >= 3 && (
  10388. // Brand new clients don't need to drop and recreate--only clients that
  10389. // potentially have corrupt data.
  10390. 0 !== n && (!function(t) {
  10391. t.deleteObjectStore("targetDocuments"), t.deleteObjectStore("targets"), t.deleteObjectStore("targetGlobal");
  10392. }(t), xo(t)), r = r.next((() =>
  10393. /**
  10394. * Creates the target global singleton row.
  10395. *
  10396. * @param txn - The version upgrade transaction for indexeddb
  10397. */
  10398. function(t) {
  10399. const e = t.store("targetGlobal"), n = {
  10400. highestTargetId: 0,
  10401. highestListenSequenceNumber: 0,
  10402. lastRemoteSnapshotVersion: st.min().toTimestamp(),
  10403. targetCount: 0
  10404. };
  10405. return e.put("targetGlobalKey", n);
  10406. }(i)))), n < 4 && s >= 4 && (0 !== n && (
  10407. // Schema version 3 uses auto-generated keys to generate globally unique
  10408. // mutation batch IDs (this was previously ensured internally by the
  10409. // client). To migrate to the new schema, we have to read all mutations
  10410. // and write them back out. We preserve the existing batch IDs to guarantee
  10411. // consistency with other object stores. Any further mutation batch IDs will
  10412. // be auto-generated.
  10413. r = r.next((() => function(t, e) {
  10414. return e.store("mutations").W().next((n => {
  10415. t.deleteObjectStore("mutations");
  10416. t.createObjectStore("mutations", {
  10417. keyPath: "batchId",
  10418. autoIncrement: !0
  10419. }).createIndex("userMutationsIndex", Ii, {
  10420. unique: !0
  10421. });
  10422. const s = e.store("mutations"), i = n.map((t => s.put(t)));
  10423. return At.waitFor(i);
  10424. }));
  10425. }(t, i)))), r = r.next((() => {
  10426. !function(t) {
  10427. t.createObjectStore("clientMetadata", {
  10428. keyPath: "clientId"
  10429. });
  10430. }(t);
  10431. }))), n < 5 && s >= 5 && (r = r.next((() => this.Us(i)))), n < 6 && s >= 6 && (r = r.next((() => (function(t) {
  10432. t.createObjectStore("remoteDocumentGlobal");
  10433. }(t), this.Ks(i))))), n < 7 && s >= 7 && (r = r.next((() => this.Gs(i)))), n < 8 && s >= 8 && (r = r.next((() => this.Qs(t, i)))),
  10434. n < 9 && s >= 9 && (r = r.next((() => {
  10435. // Multi-Tab used to manage its own changelog, but this has been moved
  10436. // to the DbRemoteDocument object store itself. Since the previous change
  10437. // log only contained transient data, we can drop its object store.
  10438. !function(t) {
  10439. t.objectStoreNames.contains("remoteDocumentChanges") && t.deleteObjectStore("remoteDocumentChanges");
  10440. }(t);
  10441. // Note: Schema version 9 used to create a read time index for the
  10442. // RemoteDocumentCache. This is now done with schema version 13.
  10443. }))), n < 10 && s >= 10 && (r = r.next((() => this.js(i)))), n < 11 && s >= 11 && (r = r.next((() => {
  10444. !function(t) {
  10445. t.createObjectStore("bundles", {
  10446. keyPath: "bundleId"
  10447. });
  10448. }(t), function(t) {
  10449. t.createObjectStore("namedQueries", {
  10450. keyPath: "name"
  10451. });
  10452. }(t);
  10453. }))), n < 12 && s >= 12 && (r = r.next((() => {
  10454. !function(t) {
  10455. const e = t.createObjectStore("documentOverlays", {
  10456. keyPath: Oi
  10457. });
  10458. e.createIndex("collectionPathOverlayIndex", Mi, {
  10459. unique: !1
  10460. }), e.createIndex("collectionGroupOverlayIndex", Fi, {
  10461. unique: !1
  10462. });
  10463. }(t);
  10464. }))), n < 13 && s >= 13 && (r = r.next((() => function(t) {
  10465. const e = t.createObjectStore("remoteDocumentsV14", {
  10466. keyPath: Ri
  10467. });
  10468. e.createIndex("documentKeyIndex", bi), e.createIndex("collectionGroupIndex", Pi);
  10469. }(t))).next((() => this.Ws(t, i))).next((() => t.deleteObjectStore("remoteDocuments")))),
  10470. n < 14 && s >= 14 && (r = r.next((() => this.zs(t, i)))), n < 15 && s >= 15 && (r = r.next((() => function(t) {
  10471. t.createObjectStore("indexConfiguration", {
  10472. keyPath: "indexId",
  10473. autoIncrement: !0
  10474. }).createIndex("collectionGroupIndex", "collectionGroup", {
  10475. unique: !1
  10476. });
  10477. t.createObjectStore("indexState", {
  10478. keyPath: Ci
  10479. }).createIndex("sequenceNumberIndex", xi, {
  10480. unique: !1
  10481. });
  10482. t.createObjectStore("indexEntries", {
  10483. keyPath: Ni
  10484. }).createIndex("documentKeyIndex", ki, {
  10485. unique: !1
  10486. });
  10487. }(t)))), r;
  10488. }
  10489. Ks(t) {
  10490. let e = 0;
  10491. return t.store("remoteDocuments").Z(((t, n) => {
  10492. e += Qr(n);
  10493. })).next((() => {
  10494. const n = {
  10495. byteSize: e
  10496. };
  10497. return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey", n);
  10498. }));
  10499. }
  10500. Us(t) {
  10501. const e = t.store("mutationQueues"), n = t.store("mutations");
  10502. return e.W().next((e => At.forEach(e, (e => {
  10503. const s = IDBKeyRange.bound([ e.userId, -1 ], [ e.userId, e.lastAcknowledgedBatchId ]);
  10504. return n.W("userMutationsIndex", s).next((n => At.forEach(n, (n => {
  10505. M(n.userId === e.userId);
  10506. const s = er(this.yt, n);
  10507. return Gr(t, e.userId, s).next((() => {}));
  10508. }))));
  10509. }))));
  10510. }
  10511. /**
  10512. * Ensures that every document in the remote document cache has a corresponding sentinel row
  10513. * with a sequence number. Missing rows are given the most recently used sequence number.
  10514. */ Gs(t) {
  10515. const e = t.store("targetDocuments"), n = t.store("remoteDocuments");
  10516. return t.store("targetGlobal").get("targetGlobalKey").next((t => {
  10517. const s = [];
  10518. return n.Z(((n, i) => {
  10519. const r = new rt(n), o = function(t) {
  10520. return [ 0, mi(t) ];
  10521. }(r);
  10522. s.push(e.get(o).next((n => n ? At.resolve() : (n => e.put({
  10523. targetId: 0,
  10524. path: mi(n),
  10525. sequenceNumber: t.highestListenSequenceNumber
  10526. }))(r))));
  10527. })).next((() => At.waitFor(s)));
  10528. }));
  10529. }
  10530. Qs(t, e) {
  10531. // Create the index.
  10532. t.createObjectStore("collectionParents", {
  10533. keyPath: Di
  10534. });
  10535. const n = e.store("collectionParents"), s = new kr, i = t => {
  10536. if (s.add(t)) {
  10537. const e = t.lastSegment(), s = t.popLast();
  10538. return n.put({
  10539. collectionId: e,
  10540. parent: mi(s)
  10541. });
  10542. }
  10543. };
  10544. // Helper to add an index entry iff we haven't already written it.
  10545. // Index existing remote documents.
  10546. return e.store("remoteDocuments").Z({
  10547. X: !0
  10548. }, ((t, e) => {
  10549. const n = new rt(t);
  10550. return i(n.popLast());
  10551. })).next((() => e.store("documentMutations").Z({
  10552. X: !0
  10553. }, (([t, e, n], s) => {
  10554. const r = pi(e);
  10555. return i(r.popLast());
  10556. }))));
  10557. }
  10558. js(t) {
  10559. const e = t.store("targets");
  10560. return e.Z(((t, n) => {
  10561. const s = nr(n), i = sr(this.yt, s);
  10562. return e.put(i);
  10563. }));
  10564. }
  10565. Ws(t, e) {
  10566. const n = e.store("remoteDocuments"), s = [];
  10567. return n.Z(((t, n) => {
  10568. const i = e.store("remoteDocumentsV14"), r = (o = n, o.document ? new ct(rt.fromString(o.document.name).popFirst(5)) : o.noDocument ? ct.fromSegments(o.noDocument.path) : o.unknownDocument ? ct.fromSegments(o.unknownDocument.path) : O()).path.toArray();
  10569. var o;
  10570. /**
  10571. * @license
  10572. * Copyright 2017 Google LLC
  10573. *
  10574. * Licensed under the Apache License, Version 2.0 (the "License");
  10575. * you may not use this file except in compliance with the License.
  10576. * You may obtain a copy of the License at
  10577. *
  10578. * http://www.apache.org/licenses/LICENSE-2.0
  10579. *
  10580. * Unless required by applicable law or agreed to in writing, software
  10581. * distributed under the License is distributed on an "AS IS" BASIS,
  10582. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10583. * See the License for the specific language governing permissions and
  10584. * limitations under the License.
  10585. */ const u = {
  10586. prefixPath: r.slice(0, r.length - 2),
  10587. collectionGroup: r[r.length - 2],
  10588. documentId: r[r.length - 1],
  10589. readTime: n.readTime || [ 0, 0 ],
  10590. unknownDocument: n.unknownDocument,
  10591. noDocument: n.noDocument,
  10592. document: n.document,
  10593. hasCommittedMutations: !!n.hasCommittedMutations
  10594. };
  10595. s.push(i.put(u));
  10596. })).next((() => At.waitFor(s)));
  10597. }
  10598. zs(t, e) {
  10599. const n = e.store("mutations"), s = ho(this.yt), i = new Vo(Do.Bs, this.yt.ie);
  10600. return n.W().next((t => {
  10601. const n = new Map;
  10602. return t.forEach((t => {
  10603. var e;
  10604. let s = null !== (e = n.get(t.userId)) && void 0 !== e ? e : Es();
  10605. er(this.yt, t).keys().forEach((t => s = s.add(t))), n.set(t.userId, s);
  10606. })), At.forEach(n, ((t, n) => {
  10607. const r = new P(n), o = lr.re(this.yt, r), u = i.getIndexManager(r), c = jr.re(r, this.yt, u, i.referenceDelegate);
  10608. return new po(s, c, o, u).recalculateAndSaveOverlaysForDocumentKeys(new Ki(e, Ot.at), t).next();
  10609. }));
  10610. }));
  10611. }
  10612. }
  10613. function xo(t) {
  10614. t.createObjectStore("targetDocuments", {
  10615. keyPath: Vi
  10616. }).createIndex("documentTargetsIndex", Si, {
  10617. unique: !0
  10618. });
  10619. // NOTE: This is unique only because the TargetId is the suffix.
  10620. t.createObjectStore("targets", {
  10621. keyPath: "targetId"
  10622. }).createIndex("queryTargetsIndex", vi, {
  10623. unique: !0
  10624. }), t.createObjectStore("targetGlobal");
  10625. }
  10626. const No = "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.";
  10627. /**
  10628. * Oldest acceptable age in milliseconds for client metadata before the client
  10629. * is considered inactive and its associated data is garbage collected.
  10630. */
  10631. /**
  10632. * An IndexedDB-backed instance of Persistence. Data is stored persistently
  10633. * across sessions.
  10634. *
  10635. * On Web only, the Firestore SDKs support shared access to its persistence
  10636. * layer. This allows multiple browser tabs to read and write to IndexedDb and
  10637. * to synchronize state even without network connectivity. Shared access is
  10638. * currently optional and not enabled unless all clients invoke
  10639. * `enablePersistence()` with `{synchronizeTabs:true}`.
  10640. *
  10641. * In multi-tab mode, if multiple clients are active at the same time, the SDK
  10642. * will designate one client as the primary client. An effort is made to pick
  10643. * a visible, network-connected and active client, and this client is
  10644. * responsible for letting other clients know about its presence. The primary
  10645. * client writes a unique client-generated identifier (the client ID) to
  10646. * IndexedDbs owner store every 4 seconds. If the primary client fails to
  10647. * update this entry, another client can acquire the lease and take over as
  10648. * primary.
  10649. *
  10650. * Some persistence operations in the SDK are designated as primary-client only
  10651. * operations. This includes the acknowledgment of mutations and all updates of
  10652. * remote documents. The effects of these operations are written to persistence
  10653. * and then broadcast to other tabs via LocalStorage (see
  10654. * `WebStorageSharedClientState`), which then refresh their state from
  10655. * persistence.
  10656. *
  10657. * Similarly, the primary client listens to notifications sent by secondary
  10658. * clients to discover persistence changes written by secondary clients, such as
  10659. * the addition of new mutations and query targets.
  10660. *
  10661. * If multi-tab is not enabled and another tab already obtained the primary
  10662. * lease, IndexedDbPersistence enters a failed state and all subsequent
  10663. * operations will automatically fail.
  10664. *
  10665. * Additionally, there is an optimization so that when a tab is closed, the
  10666. * primary lease is released immediately (this is especially important to make
  10667. * sure that a refreshed tab is able to immediately re-acquire the primary
  10668. * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload
  10669. * since it is an asynchronous API. So in addition to attempting to give up the
  10670. * lease, the leaseholder writes its client ID to a "zombiedClient" entry in
  10671. * LocalStorage which acts as an indicator that another tab should go ahead and
  10672. * take the primary lease immediately regardless of the current lease timestamp.
  10673. *
  10674. * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no
  10675. * longer optional.
  10676. */
  10677. class ko {
  10678. constructor(
  10679. /**
  10680. * Whether to synchronize the in-memory state of multiple tabs and share
  10681. * access to local persistence.
  10682. */
  10683. t, e, n, s, i, r, o, u, c,
  10684. /**
  10685. * If set to true, forcefully obtains database access. Existing tabs will
  10686. * no longer be able to access IndexedDB.
  10687. */
  10688. a, h = 15) {
  10689. if (this.allowTabSynchronization = t, this.persistenceKey = e, this.clientId = n,
  10690. this.Hs = i, this.window = r, this.document = o, this.Js = c, this.Ys = a, this.Xs = h,
  10691. this.Ss = null, this.Ds = !1, this.isPrimary = !1, this.networkEnabled = !0,
  10692. /** Our window.unload handler, if registered. */
  10693. this.Zs = null, this.inForeground = !1,
  10694. /** Our 'visibilitychange' listener if registered. */
  10695. this.ti = null,
  10696. /** The client metadata refresh task. */
  10697. this.ei = null,
  10698. /** The last time we garbage collected the client metadata object store. */
  10699. this.ni = Number.NEGATIVE_INFINITY,
  10700. /** A listener to notify on primary state changes. */
  10701. this.si = t => Promise.resolve(), !ko.C()) throw new L(B.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");
  10702. this.referenceDelegate = new oo(this, s), this.ii = e + "main", this.yt = new Hi(u),
  10703. this.ri = new bt(this.ii, this.Xs, new Co(this.yt)), this.Cs = new Xr(this.referenceDelegate, this.yt),
  10704. this.remoteDocumentCache = ho(this.yt), this.Ns = new cr, this.window && this.window.localStorage ? this.oi = this.window.localStorage : (this.oi = null,
  10705. !1 === a && x("IndexedDbPersistence", "LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."));
  10706. }
  10707. /**
  10708. * Attempt to start IndexedDb persistence.
  10709. *
  10710. * @returns Whether persistence was enabled.
  10711. */ start() {
  10712. // NOTE: This is expected to fail sometimes (in the case of another tab
  10713. // already having the persistence lock), so it's the first thing we should
  10714. // do.
  10715. return this.ui().then((() => {
  10716. if (!this.isPrimary && !this.allowTabSynchronization)
  10717. // Fail `start()` if `synchronizeTabs` is disabled and we cannot
  10718. // obtain the primary lease.
  10719. throw new L(B.FAILED_PRECONDITION, No);
  10720. return this.ci(), this.ai(), this.hi(), this.runTransaction("getHighestListenSequenceNumber", "readonly", (t => this.Cs.getHighestSequenceNumber(t)));
  10721. })).then((t => {
  10722. this.Ss = new Ot(t, this.Js);
  10723. })).then((() => {
  10724. this.Ds = !0;
  10725. })).catch((t => (this.ri && this.ri.close(), Promise.reject(t))));
  10726. }
  10727. /**
  10728. * Registers a listener that gets called when the primary state of the
  10729. * instance changes. Upon registering, this listener is invoked immediately
  10730. * with the current primary state.
  10731. *
  10732. * PORTING NOTE: This is only used for Web multi-tab.
  10733. */ li(t) {
  10734. return this.si = async e => {
  10735. if (this.started) return t(e);
  10736. }, t(this.isPrimary);
  10737. }
  10738. /**
  10739. * Registers a listener that gets called when the database receives a
  10740. * version change event indicating that it has deleted.
  10741. *
  10742. * PORTING NOTE: This is only used for Web multi-tab.
  10743. */ setDatabaseDeletedListener(t) {
  10744. this.ri.L((async e => {
  10745. // Check if an attempt is made to delete IndexedDB.
  10746. null === e.newVersion && await t();
  10747. }));
  10748. }
  10749. /**
  10750. * Adjusts the current network state in the client's metadata, potentially
  10751. * affecting the primary lease.
  10752. *
  10753. * PORTING NOTE: This is only used for Web multi-tab.
  10754. */ setNetworkEnabled(t) {
  10755. this.networkEnabled !== t && (this.networkEnabled = t,
  10756. // Schedule a primary lease refresh for immediate execution. The eventual
  10757. // lease update will be propagated via `primaryStateListener`.
  10758. this.Hs.enqueueAndForget((async () => {
  10759. this.started && await this.ui();
  10760. })));
  10761. }
  10762. /**
  10763. * Updates the client metadata in IndexedDb and attempts to either obtain or
  10764. * extend the primary lease for the local client. Asynchronously notifies the
  10765. * primary state listener if the client either newly obtained or released its
  10766. * primary lease.
  10767. */ ui() {
  10768. return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", (t => Mo(t).put({
  10769. clientId: this.clientId,
  10770. updateTimeMs: Date.now(),
  10771. networkEnabled: this.networkEnabled,
  10772. inForeground: this.inForeground
  10773. }).next((() => {
  10774. if (this.isPrimary) return this.fi(t).next((t => {
  10775. t || (this.isPrimary = !1, this.Hs.enqueueRetryable((() => this.si(!1))));
  10776. }));
  10777. })).next((() => this.di(t))).next((e => this.isPrimary && !e ? this._i(t).next((() => !1)) : !!e && this.wi(t).next((() => !0)))))).catch((t => {
  10778. if (Vt(t))
  10779. // Proceed with the existing state. Any subsequent access to
  10780. // IndexedDB will verify the lease.
  10781. return C("IndexedDbPersistence", "Failed to extend owner lease: ", t), this.isPrimary;
  10782. if (!this.allowTabSynchronization) throw t;
  10783. return C("IndexedDbPersistence", "Releasing owner lease after error during lease refresh", t),
  10784. /* isPrimary= */ !1;
  10785. })).then((t => {
  10786. this.isPrimary !== t && this.Hs.enqueueRetryable((() => this.si(t))), this.isPrimary = t;
  10787. }));
  10788. }
  10789. fi(t) {
  10790. return Oo(t).get("owner").next((t => At.resolve(this.mi(t))));
  10791. }
  10792. gi(t) {
  10793. return Mo(t).delete(this.clientId);
  10794. }
  10795. /**
  10796. * If the garbage collection threshold has passed, prunes the
  10797. * RemoteDocumentChanges and the ClientMetadata store based on the last update
  10798. * time of all clients.
  10799. */ async yi() {
  10800. if (this.isPrimary && !this.pi(this.ni, 18e5)) {
  10801. this.ni = Date.now();
  10802. const t = await this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", (t => {
  10803. const e = Gi(t, "clientMetadata");
  10804. return e.W().next((t => {
  10805. const n = this.Ii(t, 18e5), s = t.filter((t => -1 === n.indexOf(t)));
  10806. // Delete metadata for clients that are no longer considered active.
  10807. return At.forEach(s, (t => e.delete(t.clientId))).next((() => s));
  10808. }));
  10809. })).catch((() => []));
  10810. // Delete potential leftover entries that may continue to mark the
  10811. // inactive clients as zombied in LocalStorage.
  10812. // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for
  10813. // the client atomically, but we can't. So we opt to delete the IndexedDb
  10814. // entries first to avoid potentially reviving a zombied client.
  10815. if (this.oi) for (const e of t) this.oi.removeItem(this.Ti(e.clientId));
  10816. }
  10817. }
  10818. /**
  10819. * Schedules a recurring timer to update the client metadata and to either
  10820. * extend or acquire the primary lease if the client is eligible.
  10821. */ hi() {
  10822. this.ei = this.Hs.enqueueAfterDelay("client_metadata_refresh" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.ui().then((() => this.yi())).then((() => this.hi()))));
  10823. }
  10824. /** Checks whether `client` is the local client. */ mi(t) {
  10825. return !!t && t.ownerId === this.clientId;
  10826. }
  10827. /**
  10828. * Evaluate the state of all active clients and determine whether the local
  10829. * client is or can act as the holder of the primary lease. Returns whether
  10830. * the client is eligible for the lease, but does not actually acquire it.
  10831. * May return 'false' even if there is no active leaseholder and another
  10832. * (foreground) client should become leaseholder instead.
  10833. */ di(t) {
  10834. if (this.Ys) return At.resolve(!0);
  10835. return Oo(t).get("owner").next((e => {
  10836. // A client is eligible for the primary lease if:
  10837. // - its network is enabled and the client's tab is in the foreground.
  10838. // - its network is enabled and no other client's tab is in the
  10839. // foreground.
  10840. // - every clients network is disabled and the client's tab is in the
  10841. // foreground.
  10842. // - every clients network is disabled and no other client's tab is in
  10843. // the foreground.
  10844. // - the `forceOwningTab` setting was passed in.
  10845. if (null !== e && this.pi(e.leaseTimestampMs, 5e3) && !this.Ei(e.ownerId)) {
  10846. if (this.mi(e) && this.networkEnabled) return !0;
  10847. if (!this.mi(e)) {
  10848. if (!e.allowTabSynchronization)
  10849. // Fail the `canActAsPrimary` check if the current leaseholder has
  10850. // not opted into multi-tab synchronization. If this happens at
  10851. // client startup, we reject the Promise returned by
  10852. // `enablePersistence()` and the user can continue to use Firestore
  10853. // with in-memory persistence.
  10854. // If this fails during a lease refresh, we will instead block the
  10855. // AsyncQueue from executing further operations. Note that this is
  10856. // acceptable since mixing & matching different `synchronizeTabs`
  10857. // settings is not supported.
  10858. // TODO(b/114226234): Remove this check when `synchronizeTabs` can
  10859. // no longer be turned off.
  10860. throw new L(B.FAILED_PRECONDITION, No);
  10861. return !1;
  10862. }
  10863. }
  10864. return !(!this.networkEnabled || !this.inForeground) || Mo(t).W().next((t => void 0 === this.Ii(t, 5e3).find((t => {
  10865. if (this.clientId !== t.clientId) {
  10866. const e = !this.networkEnabled && t.networkEnabled, n = !this.inForeground && t.inForeground, s = this.networkEnabled === t.networkEnabled;
  10867. if (e || n && s) return !0;
  10868. }
  10869. return !1;
  10870. }))));
  10871. })).next((t => (this.isPrimary !== t && C("IndexedDbPersistence", `Client ${t ? "is" : "is not"} eligible for a primary lease.`),
  10872. t)));
  10873. }
  10874. async shutdown() {
  10875. // The shutdown() operations are idempotent and can be called even when
  10876. // start() aborted (e.g. because it couldn't acquire the persistence lease).
  10877. this.Ds = !1, this.Ai(), this.ei && (this.ei.cancel(), this.ei = null), this.Ri(),
  10878. this.bi(),
  10879. // Use `SimpleDb.runTransaction` directly to avoid failing if another tab
  10880. // has obtained the primary lease.
  10881. await this.ri.runTransaction("shutdown", "readwrite", [ "owner", "clientMetadata" ], (t => {
  10882. const e = new Ki(t, Ot.at);
  10883. return this._i(e).next((() => this.gi(e)));
  10884. })), this.ri.close(),
  10885. // Remove the entry marking the client as zombied from LocalStorage since
  10886. // we successfully deleted its metadata from IndexedDb.
  10887. this.Pi();
  10888. }
  10889. /**
  10890. * Returns clients that are not zombied and have an updateTime within the
  10891. * provided threshold.
  10892. */ Ii(t, e) {
  10893. return t.filter((t => this.pi(t.updateTimeMs, e) && !this.Ei(t.clientId)));
  10894. }
  10895. /**
  10896. * Returns the IDs of the clients that are currently active. If multi-tab
  10897. * is not supported, returns an array that only contains the local client's
  10898. * ID.
  10899. *
  10900. * PORTING NOTE: This is only used for Web multi-tab.
  10901. */ vi() {
  10902. return this.runTransaction("getActiveClients", "readonly", (t => Mo(t).W().next((t => this.Ii(t, 18e5).map((t => t.clientId))))));
  10903. }
  10904. get started() {
  10905. return this.Ds;
  10906. }
  10907. getMutationQueue(t, e) {
  10908. return jr.re(t, this.yt, e, this.referenceDelegate);
  10909. }
  10910. getTargetCache() {
  10911. return this.Cs;
  10912. }
  10913. getRemoteDocumentCache() {
  10914. return this.remoteDocumentCache;
  10915. }
  10916. getIndexManager(t) {
  10917. return new Mr(t, this.yt.ie.databaseId);
  10918. }
  10919. getDocumentOverlayCache(t) {
  10920. return lr.re(this.yt, t);
  10921. }
  10922. getBundleCache() {
  10923. return this.Ns;
  10924. }
  10925. runTransaction(t, e, n) {
  10926. C("IndexedDbPersistence", "Starting transaction:", t);
  10927. const s = "readonly" === e ? "readonly" : "readwrite", i = 15 === (r = this.Xs) ? Ui : 14 === r ? qi : 13 === r ? Li : 12 === r ? Bi : 11 === r ? $i : void O();
  10928. /** Returns the object stores for the provided schema. */
  10929. var r;
  10930. let o;
  10931. // Do all transactions as readwrite against all object stores, since we
  10932. // are the only reader/writer.
  10933. return this.ri.runTransaction(t, s, i, (s => (o = new Ki(s, this.Ss ? this.Ss.next() : Ot.at),
  10934. "readwrite-primary" === e ? this.fi(o).next((t => !!t || this.di(o))).next((e => {
  10935. if (!e) throw x(`Failed to obtain primary lease for action '${t}'.`), this.isPrimary = !1,
  10936. this.Hs.enqueueRetryable((() => this.si(!1))), new L(B.FAILED_PRECONDITION, It);
  10937. return n(o);
  10938. })).next((t => this.wi(o).next((() => t)))) : this.Vi(o).next((() => n(o)))))).then((t => (o.raiseOnCommittedEvent(),
  10939. t)));
  10940. }
  10941. /**
  10942. * Verifies that the current tab is the primary leaseholder or alternatively
  10943. * that the leaseholder has opted into multi-tab synchronization.
  10944. */
  10945. // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer
  10946. // be turned off.
  10947. Vi(t) {
  10948. return Oo(t).get("owner").next((t => {
  10949. if (null !== t && this.pi(t.leaseTimestampMs, 5e3) && !this.Ei(t.ownerId) && !this.mi(t) && !(this.Ys || this.allowTabSynchronization && t.allowTabSynchronization)) throw new L(B.FAILED_PRECONDITION, No);
  10950. }));
  10951. }
  10952. /**
  10953. * Obtains or extends the new primary lease for the local client. This
  10954. * method does not verify that the client is eligible for this lease.
  10955. */ wi(t) {
  10956. const e = {
  10957. ownerId: this.clientId,
  10958. allowTabSynchronization: this.allowTabSynchronization,
  10959. leaseTimestampMs: Date.now()
  10960. };
  10961. return Oo(t).put("owner", e);
  10962. }
  10963. static C() {
  10964. return bt.C();
  10965. }
  10966. /** Checks the primary lease and removes it if we are the current primary. */ _i(t) {
  10967. const e = Oo(t);
  10968. return e.get("owner").next((t => this.mi(t) ? (C("IndexedDbPersistence", "Releasing primary lease."),
  10969. e.delete("owner")) : At.resolve()));
  10970. }
  10971. /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ pi(t, e) {
  10972. const n = Date.now();
  10973. return !(t < n - e) && (!(t > n) || (x(`Detected an update time that is in the future: ${t} > ${n}`),
  10974. !1));
  10975. }
  10976. ci() {
  10977. null !== this.document && "function" == typeof this.document.addEventListener && (this.ti = () => {
  10978. this.Hs.enqueueAndForget((() => (this.inForeground = "visible" === this.document.visibilityState,
  10979. this.ui())));
  10980. }, this.document.addEventListener("visibilitychange", this.ti), this.inForeground = "visible" === this.document.visibilityState);
  10981. }
  10982. Ri() {
  10983. this.ti && (this.document.removeEventListener("visibilitychange", this.ti), this.ti = null);
  10984. }
  10985. /**
  10986. * Attaches a window.unload handler that will synchronously write our
  10987. * clientId to a "zombie client id" location in LocalStorage. This can be used
  10988. * by tabs trying to acquire the primary lease to determine that the lease
  10989. * is no longer valid even if the timestamp is recent. This is particularly
  10990. * important for the refresh case (so the tab correctly re-acquires the
  10991. * primary lease). LocalStorage is used for this rather than IndexedDb because
  10992. * it is a synchronous API and so can be used reliably from an unload
  10993. * handler.
  10994. */ ai() {
  10995. var t;
  10996. "function" == typeof (null === (t = this.window) || void 0 === t ? void 0 : t.addEventListener) && (this.Zs = () => {
  10997. // Note: In theory, this should be scheduled on the AsyncQueue since it
  10998. // accesses internal state. We execute this code directly during shutdown
  10999. // to make sure it gets a chance to run.
  11000. this.Ai(), isSafari() && navigator.appVersion.match(/Version\/1[45]/) &&
  11001. // On Safari 14 and 15, we do not run any cleanup actions as it might
  11002. // trigger a bug that prevents Safari from re-opening IndexedDB during
  11003. // the next page load.
  11004. // See https://bugs.webkit.org/show_bug.cgi?id=226547
  11005. this.Hs.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.Hs.enqueueAndForget((() => this.shutdown()));
  11006. }, this.window.addEventListener("pagehide", this.Zs));
  11007. }
  11008. bi() {
  11009. this.Zs && (this.window.removeEventListener("pagehide", this.Zs), this.Zs = null);
  11010. }
  11011. /**
  11012. * Returns whether a client is "zombied" based on its LocalStorage entry.
  11013. * Clients become zombied when their tab closes without running all of the
  11014. * cleanup logic in `shutdown()`.
  11015. */ Ei(t) {
  11016. var e;
  11017. try {
  11018. const n = null !== (null === (e = this.oi) || void 0 === e ? void 0 : e.getItem(this.Ti(t)));
  11019. return C("IndexedDbPersistence", `Client '${t}' ${n ? "is" : "is not"} zombied in LocalStorage`),
  11020. n;
  11021. } catch (t) {
  11022. // Gracefully handle if LocalStorage isn't working.
  11023. return x("IndexedDbPersistence", "Failed to get zombied client id.", t), !1;
  11024. }
  11025. }
  11026. /**
  11027. * Record client as zombied (a client that had its tab closed). Zombied
  11028. * clients are ignored during primary tab selection.
  11029. */ Ai() {
  11030. if (this.oi) try {
  11031. this.oi.setItem(this.Ti(this.clientId), String(Date.now()));
  11032. } catch (t) {
  11033. // Gracefully handle if LocalStorage isn't available / working.
  11034. x("Failed to set zombie client id.", t);
  11035. }
  11036. }
  11037. /** Removes the zombied client entry if it exists. */ Pi() {
  11038. if (this.oi) try {
  11039. this.oi.removeItem(this.Ti(this.clientId));
  11040. } catch (t) {
  11041. // Ignore
  11042. }
  11043. }
  11044. Ti(t) {
  11045. return `firestore_zombie_${this.persistenceKey}_${t}`;
  11046. }
  11047. }
  11048. /**
  11049. * Helper to get a typed SimpleDbStore for the primary client object store.
  11050. */ function Oo(t) {
  11051. return Gi(t, "owner");
  11052. }
  11053. /**
  11054. * Helper to get a typed SimpleDbStore for the client metadata object store.
  11055. */ function Mo(t) {
  11056. return Gi(t, "clientMetadata");
  11057. }
  11058. /**
  11059. * Generates a string used as a prefix when storing data in IndexedDB and
  11060. * LocalStorage.
  11061. */ function Fo(t, e) {
  11062. // Use two different prefix formats:
  11063. // * firestore / persistenceKey / projectID . databaseID / ...
  11064. // * firestore / persistenceKey / projectID / ...
  11065. // projectIDs are DNS-compatible names and cannot contain dots
  11066. // so there's no danger of collisions.
  11067. let n = t.projectId;
  11068. return t.isDefaultDatabase || (n += "." + t.database), "firestore/" + e + "/" + n + "/";
  11069. }
  11070. /**
  11071. * @license
  11072. * Copyright 2017 Google LLC
  11073. *
  11074. * Licensed under the Apache License, Version 2.0 (the "License");
  11075. * you may not use this file except in compliance with the License.
  11076. * You may obtain a copy of the License at
  11077. *
  11078. * http://www.apache.org/licenses/LICENSE-2.0
  11079. *
  11080. * Unless required by applicable law or agreed to in writing, software
  11081. * distributed under the License is distributed on an "AS IS" BASIS,
  11082. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11083. * See the License for the specific language governing permissions and
  11084. * limitations under the License.
  11085. */
  11086. /**
  11087. * A set of changes to what documents are currently in view and out of view for
  11088. * a given query. These changes are sent to the LocalStore by the View (via
  11089. * the SyncEngine) and are used to pin / unpin documents as appropriate.
  11090. */
  11091. class $o {
  11092. constructor(t, e, n, s) {
  11093. this.targetId = t, this.fromCache = e, this.Si = n, this.Di = s;
  11094. }
  11095. static Ci(t, e) {
  11096. let n = Es(), s = Es();
  11097. for (const t of e.docChanges) switch (t.type) {
  11098. case 0 /* ChangeType.Added */ :
  11099. n = n.add(t.doc.key);
  11100. break;
  11101. case 1 /* ChangeType.Removed */ :
  11102. s = s.add(t.doc.key);
  11103. // do nothing
  11104. }
  11105. return new $o(t, e.fromCache, n, s);
  11106. }
  11107. }
  11108. /**
  11109. * @license
  11110. * Copyright 2019 Google LLC
  11111. *
  11112. * Licensed under the Apache License, Version 2.0 (the "License");
  11113. * you may not use this file except in compliance with the License.
  11114. * You may obtain a copy of the License at
  11115. *
  11116. * http://www.apache.org/licenses/LICENSE-2.0
  11117. *
  11118. * Unless required by applicable law or agreed to in writing, software
  11119. * distributed under the License is distributed on an "AS IS" BASIS,
  11120. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11121. * See the License for the specific language governing permissions and
  11122. * limitations under the License.
  11123. */
  11124. /**
  11125. * The Firestore query engine.
  11126. *
  11127. * Firestore queries can be executed in three modes. The Query Engine determines
  11128. * what mode to use based on what data is persisted. The mode only determines
  11129. * the runtime complexity of the query - the result set is equivalent across all
  11130. * implementations.
  11131. *
  11132. * The Query engine will use indexed-based execution if a user has configured
  11133. * any index that can be used to execute query (via `setIndexConfiguration()`).
  11134. * Otherwise, the engine will try to optimize the query by re-using a previously
  11135. * persisted query result. If that is not possible, the query will be executed
  11136. * via a full collection scan.
  11137. *
  11138. * Index-based execution is the default when available. The query engine
  11139. * supports partial indexed execution and merges the result from the index
  11140. * lookup with documents that have not yet been indexed. The index evaluation
  11141. * matches the backend's format and as such, the SDK can use indexing for all
  11142. * queries that the backend supports.
  11143. *
  11144. * If no index exists, the query engine tries to take advantage of the target
  11145. * document mapping in the TargetCache. These mappings exists for all queries
  11146. * that have been synced with the backend at least once and allow the query
  11147. * engine to only read documents that previously matched a query plus any
  11148. * documents that were edited after the query was last listened to.
  11149. *
  11150. * There are some cases when this optimization is not guaranteed to produce
  11151. * the same results as full collection scans. In these cases, query
  11152. * processing falls back to full scans. These cases are:
  11153. *
  11154. * - Limit queries where a document that matched the query previously no longer
  11155. * matches the query.
  11156. *
  11157. * - Limit queries where a document edit may cause the document to sort below
  11158. * another document that is in the local cache.
  11159. *
  11160. * - Queries that have never been CURRENT or free of limbo documents.
  11161. */ class Bo {
  11162. constructor() {
  11163. this.xi = !1;
  11164. }
  11165. /** Sets the document view to query against. */ initialize(t, e) {
  11166. this.Ni = t, this.indexManager = e, this.xi = !0;
  11167. }
  11168. /** Returns all local documents matching the specified query. */ getDocumentsMatchingQuery(t, e, n, s) {
  11169. return this.ki(t, e).next((i => i || this.Oi(t, e, s, n))).next((n => n || this.Mi(t, e)));
  11170. }
  11171. /**
  11172. * Performs an indexed query that evaluates the query based on a collection's
  11173. * persisted index values. Returns `null` if an index is not available.
  11174. */ ki(t, e) {
  11175. if (fn(e))
  11176. // Queries that match all documents don't benefit from using
  11177. // key-based lookups. It is more efficient to scan all documents in a
  11178. // collection, rather than to perform individual lookups.
  11179. return At.resolve(null);
  11180. let n = gn(e);
  11181. return this.indexManager.getIndexType(t, n).next((s => 0 /* IndexType.NONE */ === s ? null : (null !== e.limit && 1 /* IndexType.PARTIAL */ === s && (
  11182. // We cannot apply a limit for targets that are served using a partial
  11183. // index. If a partial index will be used to serve the target, the
  11184. // query may return a superset of documents that match the target
  11185. // (e.g. if the index doesn't include all the target's filters), or
  11186. // may return the correct set of documents in the wrong order (e.g. if
  11187. // the index doesn't include a segment for one of the orderBys).
  11188. // Therefore, a limit should not be applied in such cases.
  11189. e = pn(e, null, "F" /* LimitType.First */), n = gn(e)), this.indexManager.getDocumentsMatchingTarget(t, n).next((s => {
  11190. const i = Es(...s);
  11191. return this.Ni.getDocuments(t, i).next((s => this.indexManager.getMinOffset(t, n).next((n => {
  11192. const r = this.Fi(e, s);
  11193. return this.$i(e, r, i, n.readTime) ? this.ki(t, pn(e, null, "F" /* LimitType.First */)) : this.Bi(t, r, e, n);
  11194. }))));
  11195. })))));
  11196. }
  11197. /**
  11198. * Performs a query based on the target's persisted query mapping. Returns
  11199. * `null` if the mapping is not available or cannot be used.
  11200. */ Oi(t, e, n, s) {
  11201. return fn(e) || s.isEqual(st.min()) ? this.Mi(t, e) : this.Ni.getDocuments(t, n).next((i => {
  11202. const r = this.Fi(e, i);
  11203. return this.$i(e, r, n, s) ? this.Mi(t, e) : (S() <= LogLevel.DEBUG && C("QueryEngine", "Re-using previous result from %s to execute query: %s", s.toString(), En(e)),
  11204. this.Bi(t, r, e, mt(s, -1)));
  11205. }));
  11206. // Queries that have never seen a snapshot without limbo free documents
  11207. // should also be run as a full collection scan.
  11208. }
  11209. /** Applies the query filter and sorting to the provided documents. */ Fi(t, e) {
  11210. // Sort the documents and re-apply the query filter since previously
  11211. // matching documents do not necessarily still match the query.
  11212. let n = new We(bn(t));
  11213. return e.forEach(((e, s) => {
  11214. An(t, s) && (n = n.add(s));
  11215. })), n;
  11216. }
  11217. /**
  11218. * Determines if a limit query needs to be refilled from cache, making it
  11219. * ineligible for index-free execution.
  11220. *
  11221. * @param query - The query.
  11222. * @param sortedPreviousResults - The documents that matched the query when it
  11223. * was last synchronized, sorted by the query's comparator.
  11224. * @param remoteKeys - The document keys that matched the query at the last
  11225. * snapshot.
  11226. * @param limboFreeSnapshotVersion - The version of the snapshot when the
  11227. * query was last synchronized.
  11228. */ $i(t, e, n, s) {
  11229. if (null === t.limit)
  11230. // Queries without limits do not need to be refilled.
  11231. return !1;
  11232. if (n.size !== e.size)
  11233. // The query needs to be refilled if a previously matching document no
  11234. // longer matches.
  11235. return !0;
  11236. // Limit queries are not eligible for index-free query execution if there is
  11237. // a potential that an older document from cache now sorts before a document
  11238. // that was previously part of the limit. This, however, can only happen if
  11239. // the document at the edge of the limit goes out of limit.
  11240. // If a document that is not the limit boundary sorts differently,
  11241. // the boundary of the limit itself did not change and documents from cache
  11242. // will continue to be "rejected" by this boundary. Therefore, we can ignore
  11243. // any modifications that don't affect the last document.
  11244. const i = "F" /* LimitType.First */ === t.limitType ? e.last() : e.first();
  11245. return !!i && (i.hasPendingWrites || i.version.compareTo(s) > 0);
  11246. }
  11247. Mi(t, e) {
  11248. return S() <= LogLevel.DEBUG && C("QueryEngine", "Using full collection scan to execute query:", En(e)),
  11249. this.Ni.getDocumentsMatchingQuery(t, e, yt.min());
  11250. }
  11251. /**
  11252. * Combines the results from an indexed execution with the remaining documents
  11253. * that have not yet been indexed.
  11254. */ Bi(t, e, n, s) {
  11255. // Retrieve all results for documents that were updated since the offset.
  11256. return this.Ni.getDocumentsMatchingQuery(t, n, s).next((t => (
  11257. // Merge with existing results
  11258. e.forEach((e => {
  11259. t = t.insert(e.key, e);
  11260. })), t)));
  11261. }
  11262. }
  11263. /**
  11264. * @license
  11265. * Copyright 2020 Google LLC
  11266. *
  11267. * Licensed under the Apache License, Version 2.0 (the "License");
  11268. * you may not use this file except in compliance with the License.
  11269. * You may obtain a copy of the License at
  11270. *
  11271. * http://www.apache.org/licenses/LICENSE-2.0
  11272. *
  11273. * Unless required by applicable law or agreed to in writing, software
  11274. * distributed under the License is distributed on an "AS IS" BASIS,
  11275. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11276. * See the License for the specific language governing permissions and
  11277. * limitations under the License.
  11278. */
  11279. /**
  11280. * Implements `LocalStore` interface.
  11281. *
  11282. * Note: some field defined in this class might have public access level, but
  11283. * the class is not exported so they are only accessible from this module.
  11284. * This is useful to implement optional features (like bundles) in free
  11285. * functions, such that they are tree-shakeable.
  11286. */
  11287. class Lo {
  11288. constructor(
  11289. /** Manages our in-memory or durable persistence. */
  11290. t, e, n, s) {
  11291. this.persistence = t, this.Li = e, this.yt = s,
  11292. /**
  11293. * Maps a targetID to data about its target.
  11294. *
  11295. * PORTING NOTE: We are using an immutable data structure on Web to make re-runs
  11296. * of `applyRemoteEvent()` idempotent.
  11297. */
  11298. this.qi = new Ge(Z),
  11299. /** Maps a target to its targetID. */
  11300. // TODO(wuandy): Evaluate if TargetId can be part of Target.
  11301. this.Ui = new ls((t => nn(t)), sn),
  11302. /**
  11303. * A per collection group index of the last read time processed by
  11304. * `getNewDocumentChanges()`.
  11305. *
  11306. * PORTING NOTE: This is only used for multi-tab synchronization.
  11307. */
  11308. this.Ki = new Map, this.Gi = t.getRemoteDocumentCache(), this.Cs = t.getTargetCache(),
  11309. this.Ns = t.getBundleCache(), this.Qi(n);
  11310. }
  11311. Qi(t) {
  11312. // TODO(indexing): Add spec tests that test these components change after a
  11313. // user change
  11314. this.documentOverlayCache = this.persistence.getDocumentOverlayCache(t), this.indexManager = this.persistence.getIndexManager(t),
  11315. this.mutationQueue = this.persistence.getMutationQueue(t, this.indexManager), this.localDocuments = new po(this.Gi, this.mutationQueue, this.documentOverlayCache, this.indexManager),
  11316. this.Gi.setIndexManager(this.indexManager), this.Li.initialize(this.localDocuments, this.indexManager);
  11317. }
  11318. collectGarbage(t) {
  11319. return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (e => t.collect(e, this.qi)));
  11320. }
  11321. }
  11322. function qo(
  11323. /** Manages our in-memory or durable persistence. */
  11324. t, e, n, s) {
  11325. return new Lo(t, e, n, s);
  11326. }
  11327. /**
  11328. * Tells the LocalStore that the currently authenticated user has changed.
  11329. *
  11330. * In response the local store switches the mutation queue to the new user and
  11331. * returns any resulting document changes.
  11332. */
  11333. // PORTING NOTE: Android and iOS only return the documents affected by the
  11334. // change.
  11335. async function Uo(t, e) {
  11336. const n = $(t);
  11337. return await n.persistence.runTransaction("Handle user change", "readonly", (t => {
  11338. // Swap out the mutation queue, grabbing the pending mutation batches
  11339. // before and after.
  11340. let s;
  11341. return n.mutationQueue.getAllMutationBatches(t).next((i => (s = i, n.Qi(e), n.mutationQueue.getAllMutationBatches(t)))).next((e => {
  11342. const i = [], r = [];
  11343. // Union the old/new changed keys.
  11344. let o = Es();
  11345. for (const t of s) {
  11346. i.push(t.batchId);
  11347. for (const e of t.mutations) o = o.add(e.key);
  11348. }
  11349. for (const t of e) {
  11350. r.push(t.batchId);
  11351. for (const e of t.mutations) o = o.add(e.key);
  11352. }
  11353. // Return the set of all (potentially) changed documents and the list
  11354. // of mutation batch IDs that were affected by change.
  11355. return n.localDocuments.getDocuments(t, o).next((t => ({
  11356. ji: t,
  11357. removedBatchIds: i,
  11358. addedBatchIds: r
  11359. })));
  11360. }));
  11361. }));
  11362. }
  11363. /* Accepts locally generated Mutations and commit them to storage. */
  11364. /**
  11365. * Acknowledges the given batch.
  11366. *
  11367. * On the happy path when a batch is acknowledged, the local store will
  11368. *
  11369. * + remove the batch from the mutation queue;
  11370. * + apply the changes to the remote document cache;
  11371. * + recalculate the latency compensated view implied by those changes (there
  11372. * may be mutations in the queue that affect the documents but haven't been
  11373. * acknowledged yet); and
  11374. * + give the changed documents back the sync engine
  11375. *
  11376. * @returns The resulting (modified) documents.
  11377. */
  11378. function Ko(t, e) {
  11379. const n = $(t);
  11380. return n.persistence.runTransaction("Acknowledge batch", "readwrite-primary", (t => {
  11381. const s = e.batch.keys(), i = n.Gi.newChangeBuffer({
  11382. trackRemovals: !0
  11383. });
  11384. return function(t, e, n, s) {
  11385. const i = n.batch, r = i.keys();
  11386. let o = At.resolve();
  11387. return r.forEach((t => {
  11388. o = o.next((() => s.getEntry(e, t))).next((e => {
  11389. const r = n.docVersions.get(t);
  11390. M(null !== r), e.version.compareTo(r) < 0 && (i.applyToRemoteDocument(e, n), e.isValidDocument() && (
  11391. // We use the commitVersion as the readTime rather than the
  11392. // document's updateTime since the updateTime is not advanced
  11393. // for updates that do not modify the underlying document.
  11394. e.setReadTime(n.commitVersion), s.addEntry(e)));
  11395. }));
  11396. })), o.next((() => t.mutationQueue.removeMutationBatch(e, i)));
  11397. }
  11398. /** Returns the local view of the documents affected by a mutation batch. */
  11399. // PORTING NOTE: Multi-Tab only.
  11400. (n, t, e, i).next((() => i.apply(t))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e.batch.batchId))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, function(t) {
  11401. let e = Es();
  11402. for (let n = 0; n < t.mutationResults.length; ++n) {
  11403. t.mutationResults[n].transformResults.length > 0 && (e = e.add(t.batch.mutations[n].key));
  11404. }
  11405. return e;
  11406. }
  11407. /**
  11408. * Removes mutations from the MutationQueue for the specified batch;
  11409. * LocalDocuments will be recalculated.
  11410. *
  11411. * @returns The resulting modified documents.
  11412. */ (e)))).next((() => n.localDocuments.getDocuments(t, s)));
  11413. }));
  11414. }
  11415. /**
  11416. * Returns the last consistent snapshot processed (used by the RemoteStore to
  11417. * determine whether to buffer incoming snapshots from the backend).
  11418. */
  11419. function Go(t) {
  11420. const e = $(t);
  11421. return e.persistence.runTransaction("Get last remote snapshot version", "readonly", (t => e.Cs.getLastRemoteSnapshotVersion(t)));
  11422. }
  11423. /**
  11424. * Updates the "ground-state" (remote) documents. We assume that the remote
  11425. * event reflects any write batches that have been acknowledged or rejected
  11426. * (i.e. we do not re-apply local mutations to updates from this event).
  11427. *
  11428. * LocalDocuments are re-calculated if there are remaining mutations in the
  11429. * queue.
  11430. */ function Qo(t, e) {
  11431. const n = $(t), s = e.snapshotVersion;
  11432. let i = n.qi;
  11433. return n.persistence.runTransaction("Apply remote event", "readwrite-primary", (t => {
  11434. const r = n.Gi.newChangeBuffer({
  11435. trackRemovals: !0
  11436. });
  11437. // Reset newTargetDataByTargetMap in case this transaction gets re-run.
  11438. i = n.qi;
  11439. const o = [];
  11440. e.targetChanges.forEach(((r, u) => {
  11441. const c = i.get(u);
  11442. if (!c) return;
  11443. // Only update the remote keys if the target is still active. This
  11444. // ensures that we can persist the updated target data along with
  11445. // the updated assignment.
  11446. o.push(n.Cs.removeMatchingKeys(t, r.removedDocuments, u).next((() => n.Cs.addMatchingKeys(t, r.addedDocuments, u))));
  11447. let a = c.withSequenceNumber(t.currentSequenceNumber);
  11448. e.targetMismatches.has(u) ? a = a.withResumeToken(Qt.EMPTY_BYTE_STRING, st.min()).withLastLimboFreeSnapshotVersion(st.min()) : r.resumeToken.approximateByteSize() > 0 && (a = a.withResumeToken(r.resumeToken, s)),
  11449. i = i.insert(u, a),
  11450. // Update the target data if there are target changes (or if
  11451. // sufficient time has passed since the last update).
  11452. /**
  11453. * Returns true if the newTargetData should be persisted during an update of
  11454. * an active target. TargetData should always be persisted when a target is
  11455. * being released and should not call this function.
  11456. *
  11457. * While the target is active, TargetData updates can be omitted when nothing
  11458. * about the target has changed except metadata like the resume token or
  11459. * snapshot version. Occasionally it's worth the extra write to prevent these
  11460. * values from getting too stale after a crash, but this doesn't have to be
  11461. * too frequent.
  11462. */
  11463. function(t, e, n) {
  11464. // Always persist target data if we don't already have a resume token.
  11465. if (0 === t.resumeToken.approximateByteSize()) return !0;
  11466. // Don't allow resume token changes to be buffered indefinitely. This
  11467. // allows us to be reasonably up-to-date after a crash and avoids needing
  11468. // to loop over all active queries on shutdown. Especially in the browser
  11469. // we may not get time to do anything interesting while the current tab is
  11470. // closing.
  11471. if (e.snapshotVersion.toMicroseconds() - t.snapshotVersion.toMicroseconds() >= 3e8) return !0;
  11472. // Otherwise if the only thing that has changed about a target is its resume
  11473. // token it's not worth persisting. Note that the RemoteStore keeps an
  11474. // in-memory view of the currently active targets which includes the current
  11475. // resume token, so stream failure or user changes will still use an
  11476. // up-to-date resume token regardless of what we do here.
  11477. return n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size > 0;
  11478. }
  11479. /**
  11480. * Notifies local store of the changed views to locally pin documents.
  11481. */ (c, a, r) && o.push(n.Cs.updateTargetData(t, a));
  11482. }));
  11483. let u = ds(), c = Es();
  11484. // HACK: The only reason we allow a null snapshot version is so that we
  11485. // can synthesize remote events when we get permission denied errors while
  11486. // trying to resolve the state of a locally cached document that is in
  11487. // limbo.
  11488. if (e.documentUpdates.forEach((s => {
  11489. e.resolvedLimboDocuments.has(s) && o.push(n.persistence.referenceDelegate.updateLimboDocument(t, s));
  11490. })),
  11491. // Each loop iteration only affects its "own" doc, so it's safe to get all
  11492. // the remote documents in advance in a single call.
  11493. o.push(jo(t, r, e.documentUpdates).next((t => {
  11494. u = t.Wi, c = t.zi;
  11495. }))), !s.isEqual(st.min())) {
  11496. const e = n.Cs.getLastRemoteSnapshotVersion(t).next((e => n.Cs.setTargetsMetadata(t, t.currentSequenceNumber, s)));
  11497. o.push(e);
  11498. }
  11499. return At.waitFor(o).next((() => r.apply(t))).next((() => n.localDocuments.getLocalViewOfDocuments(t, u, c))).next((() => u));
  11500. })).then((t => (n.qi = i, t)));
  11501. }
  11502. /**
  11503. * Populates document change buffer with documents from backend or a bundle.
  11504. * Returns the document changes resulting from applying those documents, and
  11505. * also a set of documents whose existence state are changed as a result.
  11506. *
  11507. * @param txn - Transaction to use to read existing documents from storage.
  11508. * @param documentBuffer - Document buffer to collect the resulted changes to be
  11509. * applied to storage.
  11510. * @param documents - Documents to be applied.
  11511. */ function jo(t, e, n) {
  11512. let s = Es(), i = Es();
  11513. return n.forEach((t => s = s.add(t))), e.getEntries(t, s).next((t => {
  11514. let s = ds();
  11515. return n.forEach(((n, r) => {
  11516. const o = t.get(n);
  11517. // Check if see if there is a existence state change for this document.
  11518. r.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n)),
  11519. // Note: The order of the steps below is important, since we want
  11520. // to ensure that rejected limbo resolutions (which fabricate
  11521. // NoDocuments with SnapshotVersion.min()) never add documents to
  11522. // cache.
  11523. r.isNoDocument() && r.version.isEqual(st.min()) ? (
  11524. // NoDocuments with SnapshotVersion.min() are used in manufactured
  11525. // events. We remove these documents from cache since we lost
  11526. // access.
  11527. e.removeEntry(n, r.readTime), s = s.insert(n, r)) : !o.isValidDocument() || r.version.compareTo(o.version) > 0 || 0 === r.version.compareTo(o.version) && o.hasPendingWrites ? (e.addEntry(r),
  11528. s = s.insert(n, r)) : C("LocalStore", "Ignoring outdated watch update for ", n, ". Current version:", o.version, " Watch version:", r.version);
  11529. })), {
  11530. Wi: s,
  11531. zi: i
  11532. };
  11533. }));
  11534. }
  11535. /**
  11536. * Gets the mutation batch after the passed in batchId in the mutation queue
  11537. * or null if empty.
  11538. * @param afterBatchId - If provided, the batch to search after.
  11539. * @returns The next mutation or null if there wasn't one.
  11540. */
  11541. function Wo(t, e) {
  11542. const n = $(t);
  11543. return n.persistence.runTransaction("Get next mutation batch", "readonly", (t => (void 0 === e && (e = -1),
  11544. n.mutationQueue.getNextMutationBatchAfterBatchId(t, e))));
  11545. }
  11546. /**
  11547. * Reads the current value of a Document with a given key or null if not
  11548. * found - used for testing.
  11549. */
  11550. /**
  11551. * Assigns the given target an internal ID so that its results can be pinned so
  11552. * they don't get GC'd. A target must be allocated in the local store before
  11553. * the store can be used to manage its view.
  11554. *
  11555. * Allocating an already allocated `Target` will return the existing `TargetData`
  11556. * for that `Target`.
  11557. */
  11558. function zo(t, e) {
  11559. const n = $(t);
  11560. return n.persistence.runTransaction("Allocate target", "readwrite", (t => {
  11561. let s;
  11562. return n.Cs.getTargetData(t, e).next((i => i ? (
  11563. // This target has been listened to previously, so reuse the
  11564. // previous targetID.
  11565. // TODO(mcg): freshen last accessed date?
  11566. s = i, At.resolve(s)) : n.Cs.allocateTargetId(t).next((i => (s = new zi(e, i, 0 /* TargetPurpose.Listen */ , t.currentSequenceNumber),
  11567. n.Cs.addTargetData(t, s).next((() => s)))))));
  11568. })).then((t => {
  11569. // If Multi-Tab is enabled, the existing target data may be newer than
  11570. // the in-memory data
  11571. const s = n.qi.get(t.targetId);
  11572. return (null === s || t.snapshotVersion.compareTo(s.snapshotVersion) > 0) && (n.qi = n.qi.insert(t.targetId, t),
  11573. n.Ui.set(e, t.targetId)), t;
  11574. }));
  11575. }
  11576. /**
  11577. * Returns the TargetData as seen by the LocalStore, including updates that may
  11578. * have not yet been persisted to the TargetCache.
  11579. */
  11580. // Visible for testing.
  11581. /**
  11582. * Unpins all the documents associated with the given target. If
  11583. * `keepPersistedTargetData` is set to false and Eager GC enabled, the method
  11584. * directly removes the associated target data from the target cache.
  11585. *
  11586. * Releasing a non-existing `Target` is a no-op.
  11587. */
  11588. // PORTING NOTE: `keepPersistedTargetData` is multi-tab only.
  11589. async function Ho(t, e, n) {
  11590. const s = $(t), i = s.qi.get(e), r = n ? "readwrite" : "readwrite-primary";
  11591. try {
  11592. n || await s.persistence.runTransaction("Release target", r, (t => s.persistence.referenceDelegate.removeTarget(t, i)));
  11593. } catch (t) {
  11594. if (!Vt(t)) throw t;
  11595. // All `releaseTarget` does is record the final metadata state for the
  11596. // target, but we've been recording this periodically during target
  11597. // activity. If we lose this write this could cause a very slight
  11598. // difference in the order of target deletion during GC, but we
  11599. // don't define exact LRU semantics so this is acceptable.
  11600. C("LocalStore", `Failed to update sequence numbers for target ${e}: ${t}`);
  11601. }
  11602. s.qi = s.qi.remove(e), s.Ui.delete(i.target);
  11603. }
  11604. /**
  11605. * Runs the specified query against the local store and returns the results,
  11606. * potentially taking advantage of query data from previous executions (such
  11607. * as the set of remote keys).
  11608. *
  11609. * @param usePreviousResults - Whether results from previous executions can
  11610. * be used to optimize this query execution.
  11611. */ function Jo(t, e, n) {
  11612. const s = $(t);
  11613. let i = st.min(), r = Es();
  11614. return s.persistence.runTransaction("Execute query", "readonly", (t => function(t, e, n) {
  11615. const s = $(t), i = s.Ui.get(n);
  11616. return void 0 !== i ? At.resolve(s.qi.get(i)) : s.Cs.getTargetData(e, n);
  11617. }(s, t, gn(e)).next((e => {
  11618. if (e) return i = e.lastLimboFreeSnapshotVersion, s.Cs.getMatchingKeysForTargetId(t, e.targetId).next((t => {
  11619. r = t;
  11620. }));
  11621. })).next((() => s.Li.getDocumentsMatchingQuery(t, e, n ? i : st.min(), n ? r : Es()))).next((t => (Zo(s, Rn(e), t),
  11622. {
  11623. documents: t,
  11624. Hi: r
  11625. })))));
  11626. }
  11627. // PORTING NOTE: Multi-Tab only.
  11628. function Yo(t, e) {
  11629. const n = $(t), s = $(n.Cs), i = n.qi.get(e);
  11630. return i ? Promise.resolve(i.target) : n.persistence.runTransaction("Get target data", "readonly", (t => s.ne(t, e).next((t => t ? t.target : null))));
  11631. }
  11632. /**
  11633. * Returns the set of documents that have been updated since the last call.
  11634. * If this is the first call, returns the set of changes since client
  11635. * initialization. Further invocations will return document that have changed
  11636. * since the prior call.
  11637. */
  11638. // PORTING NOTE: Multi-Tab only.
  11639. function Xo(t, e) {
  11640. const n = $(t), s = n.Ki.get(e) || st.min();
  11641. // Get the current maximum read time for the collection. This should always
  11642. // exist, but to reduce the chance for regressions we default to
  11643. // SnapshotVersion.Min()
  11644. // TODO(indexing): Consider removing the default value.
  11645. return n.persistence.runTransaction("Get new document changes", "readonly", (t => n.Gi.getAllFromCollectionGroup(t, e, mt(s, -1),
  11646. /* limit= */ Number.MAX_SAFE_INTEGER))).then((t => (Zo(n, e, t), t)));
  11647. }
  11648. /** Sets the collection group's maximum read time from the given documents. */
  11649. // PORTING NOTE: Multi-Tab only.
  11650. function Zo(t, e, n) {
  11651. let s = t.Ki.get(e) || st.min();
  11652. n.forEach(((t, e) => {
  11653. e.readTime.compareTo(s) > 0 && (s = e.readTime);
  11654. })), t.Ki.set(e, s);
  11655. }
  11656. /**
  11657. * Creates a new target using the given bundle name, which will be used to
  11658. * hold the keys of all documents from the bundle in query-document mappings.
  11659. * This ensures that the loaded documents do not get garbage collected
  11660. * right away.
  11661. */
  11662. /**
  11663. * Applies the documents from a bundle to the "ground-state" (remote)
  11664. * documents.
  11665. *
  11666. * LocalDocuments are re-calculated if there are remaining mutations in the
  11667. * queue.
  11668. */
  11669. async function tu(t, e, n, s) {
  11670. const i = $(t);
  11671. let r = Es(), o = ds();
  11672. for (const t of n) {
  11673. const n = e.Ji(t.metadata.name);
  11674. t.document && (r = r.add(n));
  11675. const s = e.Yi(t);
  11676. s.setReadTime(e.Xi(t.metadata.readTime)), o = o.insert(n, s);
  11677. }
  11678. const u = i.Gi.newChangeBuffer({
  11679. trackRemovals: !0
  11680. }), c = await zo(i, function(t) {
  11681. // It is OK that the path used for the query is not valid, because this will
  11682. // not be read and queried.
  11683. return gn(ln(rt.fromString(`__bundle__/docs/${t}`)));
  11684. }(s));
  11685. // Allocates a target to hold all document keys from the bundle, such that
  11686. // they will not get garbage collected right away.
  11687. return i.persistence.runTransaction("Apply bundle documents", "readwrite", (t => jo(t, u, o).next((e => (u.apply(t),
  11688. e))).next((e => i.Cs.removeMatchingKeysForTargetId(t, c.targetId).next((() => i.Cs.addMatchingKeys(t, r, c.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(t, e.Wi, e.zi))).next((() => e.Wi))))));
  11689. }
  11690. /**
  11691. * Returns a promise of a boolean to indicate if the given bundle has already
  11692. * been loaded and the create time is newer than the current loading bundle.
  11693. */
  11694. /**
  11695. * Saves the given `NamedQuery` to local persistence.
  11696. */
  11697. async function eu(t, e, n = Es()) {
  11698. // Allocate a target for the named query such that it can be resumed
  11699. // from associated read time if users use it to listen.
  11700. // NOTE: this also means if no corresponding target exists, the new target
  11701. // will remain active and will not get collected, unless users happen to
  11702. // unlisten the query somehow.
  11703. const s = await zo(t, gn(ir(e.bundledQuery))), i = $(t);
  11704. return i.persistence.runTransaction("Save named query", "readwrite", (t => {
  11705. const r = qs(e.readTime);
  11706. // Simply save the query itself if it is older than what the SDK already
  11707. // has.
  11708. if (s.snapshotVersion.compareTo(r) >= 0) return i.Ns.saveNamedQuery(t, e);
  11709. // Update existing target data because the query from the bundle is newer.
  11710. const o = s.withResumeToken(Qt.EMPTY_BYTE_STRING, r);
  11711. return i.qi = i.qi.insert(o.targetId, o), i.Cs.updateTargetData(t, o).next((() => i.Cs.removeMatchingKeysForTargetId(t, s.targetId))).next((() => i.Cs.addMatchingKeys(t, n, s.targetId))).next((() => i.Ns.saveNamedQuery(t, e)));
  11712. }));
  11713. }
  11714. /** Assembles the key for a client state in WebStorage */
  11715. function nu(t, e) {
  11716. return `firestore_clients_${t}_${e}`;
  11717. }
  11718. // The format of the WebStorage key that stores the mutation state is:
  11719. // firestore_mutations_<persistence_prefix>_<batch_id>
  11720. // (for unauthenticated users)
  11721. // or: firestore_mutations_<persistence_prefix>_<batch_id>_<user_uid>
  11722. // 'user_uid' is last to avoid needing to escape '_' characters that it might
  11723. // contain.
  11724. /** Assembles the key for a mutation batch in WebStorage */
  11725. function su(t, e, n) {
  11726. let s = `firestore_mutations_${t}_${n}`;
  11727. return e.isAuthenticated() && (s += `_${e.uid}`), s;
  11728. }
  11729. // The format of the WebStorage key that stores a query target's metadata is:
  11730. // firestore_targets_<persistence_prefix>_<target_id>
  11731. /** Assembles the key for a query state in WebStorage */
  11732. function iu(t, e) {
  11733. return `firestore_targets_${t}_${e}`;
  11734. }
  11735. // The WebStorage prefix that stores the primary tab's online state. The
  11736. // format of the key is:
  11737. // firestore_online_state_<persistence_prefix>
  11738. /**
  11739. * Holds the state of a mutation batch, including its user ID, batch ID and
  11740. * whether the batch is 'pending', 'acknowledged' or 'rejected'.
  11741. */
  11742. // Visible for testing
  11743. class ru {
  11744. constructor(t, e, n, s) {
  11745. this.user = t, this.batchId = e, this.state = n, this.error = s;
  11746. }
  11747. /**
  11748. * Parses a MutationMetadata from its JSON representation in WebStorage.
  11749. * Logs a warning and returns null if the format of the data is not valid.
  11750. */ static Zi(t, e, n) {
  11751. const s = JSON.parse(n);
  11752. let i, r = "object" == typeof s && -1 !== [ "pending", "acknowledged", "rejected" ].indexOf(s.state) && (void 0 === s.error || "object" == typeof s.error);
  11753. return r && s.error && (r = "string" == typeof s.error.message && "string" == typeof s.error.code,
  11754. r && (i = new L(s.error.code, s.error.message))), r ? new ru(t, e, s.state, i) : (x("SharedClientState", `Failed to parse mutation state for ID '${e}': ${n}`),
  11755. null);
  11756. }
  11757. tr() {
  11758. const t = {
  11759. state: this.state,
  11760. updateTimeMs: Date.now()
  11761. };
  11762. return this.error && (t.error = {
  11763. code: this.error.code,
  11764. message: this.error.message
  11765. }), JSON.stringify(t);
  11766. }
  11767. }
  11768. /**
  11769. * Holds the state of a query target, including its target ID and whether the
  11770. * target is 'not-current', 'current' or 'rejected'.
  11771. */
  11772. // Visible for testing
  11773. class ou {
  11774. constructor(t, e, n) {
  11775. this.targetId = t, this.state = e, this.error = n;
  11776. }
  11777. /**
  11778. * Parses a QueryTargetMetadata from its JSON representation in WebStorage.
  11779. * Logs a warning and returns null if the format of the data is not valid.
  11780. */ static Zi(t, e) {
  11781. const n = JSON.parse(e);
  11782. let s, i = "object" == typeof n && -1 !== [ "not-current", "current", "rejected" ].indexOf(n.state) && (void 0 === n.error || "object" == typeof n.error);
  11783. return i && n.error && (i = "string" == typeof n.error.message && "string" == typeof n.error.code,
  11784. i && (s = new L(n.error.code, n.error.message))), i ? new ou(t, n.state, s) : (x("SharedClientState", `Failed to parse target state for ID '${t}': ${e}`),
  11785. null);
  11786. }
  11787. tr() {
  11788. const t = {
  11789. state: this.state,
  11790. updateTimeMs: Date.now()
  11791. };
  11792. return this.error && (t.error = {
  11793. code: this.error.code,
  11794. message: this.error.message
  11795. }), JSON.stringify(t);
  11796. }
  11797. }
  11798. /**
  11799. * This class represents the immutable ClientState for a client read from
  11800. * WebStorage, containing the list of active query targets.
  11801. */ class uu {
  11802. constructor(t, e) {
  11803. this.clientId = t, this.activeTargetIds = e;
  11804. }
  11805. /**
  11806. * Parses a RemoteClientState from the JSON representation in WebStorage.
  11807. * Logs a warning and returns null if the format of the data is not valid.
  11808. */ static Zi(t, e) {
  11809. const n = JSON.parse(e);
  11810. let s = "object" == typeof n && n.activeTargetIds instanceof Array, i = Rs();
  11811. for (let t = 0; s && t < n.activeTargetIds.length; ++t) s = Kt(n.activeTargetIds[t]),
  11812. i = i.add(n.activeTargetIds[t]);
  11813. return s ? new uu(t, i) : (x("SharedClientState", `Failed to parse client data for instance '${t}': ${e}`),
  11814. null);
  11815. }
  11816. }
  11817. /**
  11818. * This class represents the online state for all clients participating in
  11819. * multi-tab. The online state is only written to by the primary client, and
  11820. * used in secondary clients to update their query views.
  11821. */ class cu {
  11822. constructor(t, e) {
  11823. this.clientId = t, this.onlineState = e;
  11824. }
  11825. /**
  11826. * Parses a SharedOnlineState from its JSON representation in WebStorage.
  11827. * Logs a warning and returns null if the format of the data is not valid.
  11828. */ static Zi(t) {
  11829. const e = JSON.parse(t);
  11830. return "object" == typeof e && -1 !== [ "Unknown", "Online", "Offline" ].indexOf(e.onlineState) && "string" == typeof e.clientId ? new cu(e.clientId, e.onlineState) : (x("SharedClientState", `Failed to parse online state: ${t}`),
  11831. null);
  11832. }
  11833. }
  11834. /**
  11835. * Metadata state of the local client. Unlike `RemoteClientState`, this class is
  11836. * mutable and keeps track of all pending mutations, which allows us to
  11837. * update the range of pending mutation batch IDs as new mutations are added or
  11838. * removed.
  11839. *
  11840. * The data in `LocalClientState` is not read from WebStorage and instead
  11841. * updated via its instance methods. The updated state can be serialized via
  11842. * `toWebStorageJSON()`.
  11843. */
  11844. // Visible for testing.
  11845. class au {
  11846. constructor() {
  11847. this.activeTargetIds = Rs();
  11848. }
  11849. er(t) {
  11850. this.activeTargetIds = this.activeTargetIds.add(t);
  11851. }
  11852. nr(t) {
  11853. this.activeTargetIds = this.activeTargetIds.delete(t);
  11854. }
  11855. /**
  11856. * Converts this entry into a JSON-encoded format we can use for WebStorage.
  11857. * Does not encode `clientId` as it is part of the key in WebStorage.
  11858. */ tr() {
  11859. const t = {
  11860. activeTargetIds: this.activeTargetIds.toArray(),
  11861. updateTimeMs: Date.now()
  11862. };
  11863. return JSON.stringify(t);
  11864. }
  11865. }
  11866. /**
  11867. * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the
  11868. * backing store for the SharedClientState. It keeps track of all active
  11869. * clients and supports modifications of the local client's data.
  11870. */ class hu {
  11871. constructor(t, e, n, s, i) {
  11872. this.window = t, this.Hs = e, this.persistenceKey = n, this.sr = s, this.syncEngine = null,
  11873. this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.ir = this.rr.bind(this),
  11874. this.ur = new Ge(Z), this.started = !1,
  11875. /**
  11876. * Captures WebStorage events that occur before `start()` is called. These
  11877. * events are replayed once `WebStorageSharedClientState` is started.
  11878. */
  11879. this.cr = [];
  11880. // Escape the special characters mentioned here:
  11881. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
  11882. const r = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  11883. this.storage = this.window.localStorage, this.currentUser = i, this.ar = nu(this.persistenceKey, this.sr),
  11884. this.hr =
  11885. /** Assembles the key for the current sequence number. */
  11886. function(t) {
  11887. return `firestore_sequence_number_${t}`;
  11888. }
  11889. /**
  11890. * @license
  11891. * Copyright 2018 Google LLC
  11892. *
  11893. * Licensed under the Apache License, Version 2.0 (the "License");
  11894. * you may not use this file except in compliance with the License.
  11895. * You may obtain a copy of the License at
  11896. *
  11897. * http://www.apache.org/licenses/LICENSE-2.0
  11898. *
  11899. * Unless required by applicable law or agreed to in writing, software
  11900. * distributed under the License is distributed on an "AS IS" BASIS,
  11901. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11902. * See the License for the specific language governing permissions and
  11903. * limitations under the License.
  11904. */ (this.persistenceKey), this.ur = this.ur.insert(this.sr, new au), this.lr = new RegExp(`^firestore_clients_${r}_([^_]*)$`),
  11905. this.dr = new RegExp(`^firestore_mutations_${r}_(\\d+)(?:_(.*))?$`), this._r = new RegExp(`^firestore_targets_${r}_(\\d+)$`),
  11906. this.wr =
  11907. /** Assembles the key for the online state of the primary tab. */
  11908. function(t) {
  11909. return `firestore_online_state_${t}`;
  11910. }
  11911. // The WebStorage prefix that plays as a event to indicate the remote documents
  11912. // might have changed due to some secondary tabs loading a bundle.
  11913. // format of the key is:
  11914. // firestore_bundle_loaded_v2_<persistenceKey>
  11915. // The version ending with "v2" stores the list of modified collection groups.
  11916. (this.persistenceKey), this.mr = function(t) {
  11917. return `firestore_bundle_loaded_v2_${t}`;
  11918. }
  11919. // The WebStorage key prefix for the key that stores the last sequence number allocated. The key
  11920. // looks like 'firestore_sequence_number_<persistence_prefix>'.
  11921. (this.persistenceKey),
  11922. // Rather than adding the storage observer during start(), we add the
  11923. // storage observer during initialization. This ensures that we collect
  11924. // events before other components populate their initial state (during their
  11925. // respective start() calls). Otherwise, we might for example miss a
  11926. // mutation that is added after LocalStore's start() processed the existing
  11927. // mutations but before we observe WebStorage events.
  11928. this.window.addEventListener("storage", this.ir);
  11929. }
  11930. /** Returns 'true' if WebStorage is available in the current environment. */ static C(t) {
  11931. return !(!t || !t.localStorage);
  11932. }
  11933. async start() {
  11934. // Retrieve the list of existing clients to backfill the data in
  11935. // SharedClientState.
  11936. const t = await this.syncEngine.vi();
  11937. for (const e of t) {
  11938. if (e === this.sr) continue;
  11939. const t = this.getItem(nu(this.persistenceKey, e));
  11940. if (t) {
  11941. const n = uu.Zi(e, t);
  11942. n && (this.ur = this.ur.insert(n.clientId, n));
  11943. }
  11944. }
  11945. this.gr();
  11946. // Check if there is an existing online state and call the callback handler
  11947. // if applicable.
  11948. const e = this.storage.getItem(this.wr);
  11949. if (e) {
  11950. const t = this.yr(e);
  11951. t && this.pr(t);
  11952. }
  11953. for (const t of this.cr) this.rr(t);
  11954. this.cr = [],
  11955. // Register a window unload hook to remove the client metadata entry from
  11956. // WebStorage even if `shutdown()` was not called.
  11957. this.window.addEventListener("pagehide", (() => this.shutdown())), this.started = !0;
  11958. }
  11959. writeSequenceNumber(t) {
  11960. this.setItem(this.hr, JSON.stringify(t));
  11961. }
  11962. getAllActiveQueryTargets() {
  11963. return this.Ir(this.ur);
  11964. }
  11965. isActiveQueryTarget(t) {
  11966. let e = !1;
  11967. return this.ur.forEach(((n, s) => {
  11968. s.activeTargetIds.has(t) && (e = !0);
  11969. })), e;
  11970. }
  11971. addPendingMutation(t) {
  11972. this.Tr(t, "pending");
  11973. }
  11974. updateMutationState(t, e, n) {
  11975. this.Tr(t, e, n),
  11976. // Once a final mutation result is observed by other clients, they no longer
  11977. // access the mutation's metadata entry. Since WebStorage replays events
  11978. // in order, it is safe to delete the entry right after updating it.
  11979. this.Er(t);
  11980. }
  11981. addLocalQueryTarget(t) {
  11982. let e = "not-current";
  11983. // Lookup an existing query state if the target ID was already registered
  11984. // by another tab
  11985. if (this.isActiveQueryTarget(t)) {
  11986. const n = this.storage.getItem(iu(this.persistenceKey, t));
  11987. if (n) {
  11988. const s = ou.Zi(t, n);
  11989. s && (e = s.state);
  11990. }
  11991. }
  11992. return this.Ar.er(t), this.gr(), e;
  11993. }
  11994. removeLocalQueryTarget(t) {
  11995. this.Ar.nr(t), this.gr();
  11996. }
  11997. isLocalQueryTarget(t) {
  11998. return this.Ar.activeTargetIds.has(t);
  11999. }
  12000. clearQueryState(t) {
  12001. this.removeItem(iu(this.persistenceKey, t));
  12002. }
  12003. updateQueryState(t, e, n) {
  12004. this.Rr(t, e, n);
  12005. }
  12006. handleUserChange(t, e, n) {
  12007. e.forEach((t => {
  12008. this.Er(t);
  12009. })), this.currentUser = t, n.forEach((t => {
  12010. this.addPendingMutation(t);
  12011. }));
  12012. }
  12013. setOnlineState(t) {
  12014. this.br(t);
  12015. }
  12016. notifyBundleLoaded(t) {
  12017. this.Pr(t);
  12018. }
  12019. shutdown() {
  12020. this.started && (this.window.removeEventListener("storage", this.ir), this.removeItem(this.ar),
  12021. this.started = !1);
  12022. }
  12023. getItem(t) {
  12024. const e = this.storage.getItem(t);
  12025. return C("SharedClientState", "READ", t, e), e;
  12026. }
  12027. setItem(t, e) {
  12028. C("SharedClientState", "SET", t, e), this.storage.setItem(t, e);
  12029. }
  12030. removeItem(t) {
  12031. C("SharedClientState", "REMOVE", t), this.storage.removeItem(t);
  12032. }
  12033. rr(t) {
  12034. // Note: The function is typed to take Event to be interface-compatible with
  12035. // `Window.addEventListener`.
  12036. const e = t;
  12037. if (e.storageArea === this.storage) {
  12038. if (C("SharedClientState", "EVENT", e.key, e.newValue), e.key === this.ar) return void x("Received WebStorage notification for local change. Another client might have garbage-collected our state");
  12039. this.Hs.enqueueRetryable((async () => {
  12040. if (this.started) {
  12041. if (null !== e.key) if (this.lr.test(e.key)) {
  12042. if (null == e.newValue) {
  12043. const t = this.vr(e.key);
  12044. return this.Vr(t, null);
  12045. }
  12046. {
  12047. const t = this.Sr(e.key, e.newValue);
  12048. if (t) return this.Vr(t.clientId, t);
  12049. }
  12050. } else if (this.dr.test(e.key)) {
  12051. if (null !== e.newValue) {
  12052. const t = this.Dr(e.key, e.newValue);
  12053. if (t) return this.Cr(t);
  12054. }
  12055. } else if (this._r.test(e.key)) {
  12056. if (null !== e.newValue) {
  12057. const t = this.Nr(e.key, e.newValue);
  12058. if (t) return this.kr(t);
  12059. }
  12060. } else if (e.key === this.wr) {
  12061. if (null !== e.newValue) {
  12062. const t = this.yr(e.newValue);
  12063. if (t) return this.pr(t);
  12064. }
  12065. } else if (e.key === this.hr) {
  12066. const t = function(t) {
  12067. let e = Ot.at;
  12068. if (null != t) try {
  12069. const n = JSON.parse(t);
  12070. M("number" == typeof n), e = n;
  12071. } catch (t) {
  12072. x("SharedClientState", "Failed to read sequence number from WebStorage", t);
  12073. }
  12074. return e;
  12075. }
  12076. /**
  12077. * `MemorySharedClientState` is a simple implementation of SharedClientState for
  12078. * clients using memory persistence. The state in this class remains fully
  12079. * isolated and no synchronization is performed.
  12080. */ (e.newValue);
  12081. t !== Ot.at && this.sequenceNumberHandler(t);
  12082. } else if (e.key === this.mr) {
  12083. const t = this.Or(e.newValue);
  12084. await Promise.all(t.map((t => this.syncEngine.Mr(t))));
  12085. }
  12086. } else this.cr.push(e);
  12087. }));
  12088. }
  12089. }
  12090. get Ar() {
  12091. return this.ur.get(this.sr);
  12092. }
  12093. gr() {
  12094. this.setItem(this.ar, this.Ar.tr());
  12095. }
  12096. Tr(t, e, n) {
  12097. const s = new ru(this.currentUser, t, e, n), i = su(this.persistenceKey, this.currentUser, t);
  12098. this.setItem(i, s.tr());
  12099. }
  12100. Er(t) {
  12101. const e = su(this.persistenceKey, this.currentUser, t);
  12102. this.removeItem(e);
  12103. }
  12104. br(t) {
  12105. const e = {
  12106. clientId: this.sr,
  12107. onlineState: t
  12108. };
  12109. this.storage.setItem(this.wr, JSON.stringify(e));
  12110. }
  12111. Rr(t, e, n) {
  12112. const s = iu(this.persistenceKey, t), i = new ou(t, e, n);
  12113. this.setItem(s, i.tr());
  12114. }
  12115. Pr(t) {
  12116. const e = JSON.stringify(Array.from(t));
  12117. this.setItem(this.mr, e);
  12118. }
  12119. /**
  12120. * Parses a client state key in WebStorage. Returns null if the key does not
  12121. * match the expected key format.
  12122. */ vr(t) {
  12123. const e = this.lr.exec(t);
  12124. return e ? e[1] : null;
  12125. }
  12126. /**
  12127. * Parses a client state in WebStorage. Returns 'null' if the value could not
  12128. * be parsed.
  12129. */ Sr(t, e) {
  12130. const n = this.vr(t);
  12131. return uu.Zi(n, e);
  12132. }
  12133. /**
  12134. * Parses a mutation batch state in WebStorage. Returns 'null' if the value
  12135. * could not be parsed.
  12136. */ Dr(t, e) {
  12137. const n = this.dr.exec(t), s = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;
  12138. return ru.Zi(new P(i), s, e);
  12139. }
  12140. /**
  12141. * Parses a query target state from WebStorage. Returns 'null' if the value
  12142. * could not be parsed.
  12143. */ Nr(t, e) {
  12144. const n = this._r.exec(t), s = Number(n[1]);
  12145. return ou.Zi(s, e);
  12146. }
  12147. /**
  12148. * Parses an online state from WebStorage. Returns 'null' if the value
  12149. * could not be parsed.
  12150. */ yr(t) {
  12151. return cu.Zi(t);
  12152. }
  12153. Or(t) {
  12154. return JSON.parse(t);
  12155. }
  12156. async Cr(t) {
  12157. if (t.user.uid === this.currentUser.uid) return this.syncEngine.Fr(t.batchId, t.state, t.error);
  12158. C("SharedClientState", `Ignoring mutation for non-active user ${t.user.uid}`);
  12159. }
  12160. kr(t) {
  12161. return this.syncEngine.$r(t.targetId, t.state, t.error);
  12162. }
  12163. Vr(t, e) {
  12164. const n = e ? this.ur.insert(t, e) : this.ur.remove(t), s = this.Ir(this.ur), i = this.Ir(n), r = [], o = [];
  12165. return i.forEach((t => {
  12166. s.has(t) || r.push(t);
  12167. })), s.forEach((t => {
  12168. i.has(t) || o.push(t);
  12169. })), this.syncEngine.Br(r, o).then((() => {
  12170. this.ur = n;
  12171. }));
  12172. }
  12173. pr(t) {
  12174. // We check whether the client that wrote this online state is still active
  12175. // by comparing its client ID to the list of clients kept active in
  12176. // IndexedDb. If a client does not update their IndexedDb client state
  12177. // within 5 seconds, it is considered inactive and we don't emit an online
  12178. // state event.
  12179. this.ur.get(t.clientId) && this.onlineStateHandler(t.onlineState);
  12180. }
  12181. Ir(t) {
  12182. let e = Rs();
  12183. return t.forEach(((t, n) => {
  12184. e = e.unionWith(n.activeTargetIds);
  12185. })), e;
  12186. }
  12187. }
  12188. class lu {
  12189. constructor() {
  12190. this.Lr = new au, this.qr = {}, this.onlineStateHandler = null, this.sequenceNumberHandler = null;
  12191. }
  12192. addPendingMutation(t) {
  12193. // No op.
  12194. }
  12195. updateMutationState(t, e, n) {
  12196. // No op.
  12197. }
  12198. addLocalQueryTarget(t) {
  12199. return this.Lr.er(t), this.qr[t] || "not-current";
  12200. }
  12201. updateQueryState(t, e, n) {
  12202. this.qr[t] = e;
  12203. }
  12204. removeLocalQueryTarget(t) {
  12205. this.Lr.nr(t);
  12206. }
  12207. isLocalQueryTarget(t) {
  12208. return this.Lr.activeTargetIds.has(t);
  12209. }
  12210. clearQueryState(t) {
  12211. delete this.qr[t];
  12212. }
  12213. getAllActiveQueryTargets() {
  12214. return this.Lr.activeTargetIds;
  12215. }
  12216. isActiveQueryTarget(t) {
  12217. return this.Lr.activeTargetIds.has(t);
  12218. }
  12219. start() {
  12220. return this.Lr = new au, Promise.resolve();
  12221. }
  12222. handleUserChange(t, e, n) {
  12223. // No op.
  12224. }
  12225. setOnlineState(t) {
  12226. // No op.
  12227. }
  12228. shutdown() {}
  12229. writeSequenceNumber(t) {}
  12230. notifyBundleLoaded(t) {
  12231. // No op.
  12232. }
  12233. }
  12234. /**
  12235. * @license
  12236. * Copyright 2019 Google LLC
  12237. *
  12238. * Licensed under the Apache License, Version 2.0 (the "License");
  12239. * you may not use this file except in compliance with the License.
  12240. * You may obtain a copy of the License at
  12241. *
  12242. * http://www.apache.org/licenses/LICENSE-2.0
  12243. *
  12244. * Unless required by applicable law or agreed to in writing, software
  12245. * distributed under the License is distributed on an "AS IS" BASIS,
  12246. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12247. * See the License for the specific language governing permissions and
  12248. * limitations under the License.
  12249. */ class fu {
  12250. Ur(t) {
  12251. // No-op.
  12252. }
  12253. shutdown() {
  12254. // No-op.
  12255. }
  12256. }
  12257. /**
  12258. * @license
  12259. * Copyright 2019 Google LLC
  12260. *
  12261. * Licensed under the Apache License, Version 2.0 (the "License");
  12262. * you may not use this file except in compliance with the License.
  12263. * You may obtain a copy of the License at
  12264. *
  12265. * http://www.apache.org/licenses/LICENSE-2.0
  12266. *
  12267. * Unless required by applicable law or agreed to in writing, software
  12268. * distributed under the License is distributed on an "AS IS" BASIS,
  12269. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12270. * See the License for the specific language governing permissions and
  12271. * limitations under the License.
  12272. */
  12273. // References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()
  12274. /* eslint-disable no-restricted-globals */
  12275. /**
  12276. * Browser implementation of ConnectivityMonitor.
  12277. */
  12278. class du {
  12279. constructor() {
  12280. this.Kr = () => this.Gr(), this.Qr = () => this.jr(), this.Wr = [], this.zr();
  12281. }
  12282. Ur(t) {
  12283. this.Wr.push(t);
  12284. }
  12285. shutdown() {
  12286. window.removeEventListener("online", this.Kr), window.removeEventListener("offline", this.Qr);
  12287. }
  12288. zr() {
  12289. window.addEventListener("online", this.Kr), window.addEventListener("offline", this.Qr);
  12290. }
  12291. Gr() {
  12292. C("ConnectivityMonitor", "Network connectivity changed: AVAILABLE");
  12293. for (const t of this.Wr) t(0 /* NetworkStatus.AVAILABLE */);
  12294. }
  12295. jr() {
  12296. C("ConnectivityMonitor", "Network connectivity changed: UNAVAILABLE");
  12297. for (const t of this.Wr) t(1 /* NetworkStatus.UNAVAILABLE */);
  12298. }
  12299. // TODO(chenbrian): Consider passing in window either into this component or
  12300. // here for testing via FakeWindow.
  12301. /** Checks that all used attributes of window are available. */
  12302. static C() {
  12303. return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;
  12304. }
  12305. }
  12306. /**
  12307. * @license
  12308. * Copyright 2020 Google LLC
  12309. *
  12310. * Licensed under the Apache License, Version 2.0 (the "License");
  12311. * you may not use this file except in compliance with the License.
  12312. * You may obtain a copy of the License at
  12313. *
  12314. * http://www.apache.org/licenses/LICENSE-2.0
  12315. *
  12316. * Unless required by applicable law or agreed to in writing, software
  12317. * distributed under the License is distributed on an "AS IS" BASIS,
  12318. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12319. * See the License for the specific language governing permissions and
  12320. * limitations under the License.
  12321. */ const _u = {
  12322. BatchGetDocuments: "batchGet",
  12323. Commit: "commit",
  12324. RunQuery: "runQuery",
  12325. RunAggregationQuery: "runAggregationQuery"
  12326. };
  12327. /**
  12328. * Maps RPC names to the corresponding REST endpoint name.
  12329. *
  12330. * We use array notation to avoid mangling.
  12331. */
  12332. /**
  12333. * @license
  12334. * Copyright 2017 Google LLC
  12335. *
  12336. * Licensed under the Apache License, Version 2.0 (the "License");
  12337. * you may not use this file except in compliance with the License.
  12338. * You may obtain a copy of the License at
  12339. *
  12340. * http://www.apache.org/licenses/LICENSE-2.0
  12341. *
  12342. * Unless required by applicable law or agreed to in writing, software
  12343. * distributed under the License is distributed on an "AS IS" BASIS,
  12344. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12345. * See the License for the specific language governing permissions and
  12346. * limitations under the License.
  12347. */
  12348. /**
  12349. * Provides a simple helper class that implements the Stream interface to
  12350. * bridge to other implementations that are streams but do not implement the
  12351. * interface. The stream callbacks are invoked with the callOn... methods.
  12352. */
  12353. class wu {
  12354. constructor(t) {
  12355. this.Hr = t.Hr, this.Jr = t.Jr;
  12356. }
  12357. Yr(t) {
  12358. this.Xr = t;
  12359. }
  12360. Zr(t) {
  12361. this.eo = t;
  12362. }
  12363. onMessage(t) {
  12364. this.no = t;
  12365. }
  12366. close() {
  12367. this.Jr();
  12368. }
  12369. send(t) {
  12370. this.Hr(t);
  12371. }
  12372. so() {
  12373. this.Xr();
  12374. }
  12375. io(t) {
  12376. this.eo(t);
  12377. }
  12378. ro(t) {
  12379. this.no(t);
  12380. }
  12381. }
  12382. /**
  12383. * @license
  12384. * Copyright 2017 Google LLC
  12385. *
  12386. * Licensed under the Apache License, Version 2.0 (the "License");
  12387. * you may not use this file except in compliance with the License.
  12388. * You may obtain a copy of the License at
  12389. *
  12390. * http://www.apache.org/licenses/LICENSE-2.0
  12391. *
  12392. * Unless required by applicable law or agreed to in writing, software
  12393. * distributed under the License is distributed on an "AS IS" BASIS,
  12394. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12395. * See the License for the specific language governing permissions and
  12396. * limitations under the License.
  12397. */ class mu extends
  12398. /**
  12399. * Base class for all Rest-based connections to the backend (WebChannel and
  12400. * HTTP).
  12401. */
  12402. class {
  12403. constructor(t) {
  12404. this.databaseInfo = t, this.databaseId = t.databaseId;
  12405. const e = t.ssl ? "https" : "http";
  12406. this.oo = e + "://" + t.host, this.uo = "projects/" + this.databaseId.projectId + "/databases/" + this.databaseId.database + "/documents";
  12407. }
  12408. get co() {
  12409. // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine
  12410. // where to run the query, and expect the `request` to NOT specify the "path".
  12411. return !1;
  12412. }
  12413. ao(t, e, n, s, i) {
  12414. const r = this.ho(t, e);
  12415. C("RestConnection", "Sending: ", r, n);
  12416. const o = {};
  12417. return this.lo(o, s, i), this.fo(t, r, o, n).then((t => (C("RestConnection", "Received: ", t),
  12418. t)), (e => {
  12419. throw N("RestConnection", `${t} failed with error: `, e, "url: ", r, "request:", n),
  12420. e;
  12421. }));
  12422. }
  12423. _o(t, e, n, s, i, r) {
  12424. // The REST API automatically aggregates all of the streamed results, so we
  12425. // can just use the normal invoke() method.
  12426. return this.ao(t, e, n, s, i);
  12427. }
  12428. /**
  12429. * Modifies the headers for a request, adding any authorization token if
  12430. * present and any additional headers for the request.
  12431. */ lo(t, e, n) {
  12432. t["X-Goog-Api-Client"] = "gl-js/ fire/" + v,
  12433. // Content-Type: text/plain will avoid preflight requests which might
  12434. // mess with CORS and redirects by proxies. If we add custom headers
  12435. // we will need to change this code to potentially use the $httpOverwrite
  12436. // parameter supported by ESF to avoid triggering preflight requests.
  12437. t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId),
  12438. e && e.headers.forEach(((e, n) => t[n] = e)), n && n.headers.forEach(((e, n) => t[n] = e));
  12439. }
  12440. ho(t, e) {
  12441. const n = _u[t];
  12442. return `${this.oo}/v1/${e}:${n}`;
  12443. }
  12444. } {
  12445. constructor(t) {
  12446. super(t), this.forceLongPolling = t.forceLongPolling, this.autoDetectLongPolling = t.autoDetectLongPolling,
  12447. this.useFetchStreams = t.useFetchStreams;
  12448. }
  12449. fo(t, e, n, s) {
  12450. return new Promise(((i, r) => {
  12451. const o = new XhrIo;
  12452. o.setWithCredentials(!0), o.listenOnce(EventType.COMPLETE, (() => {
  12453. try {
  12454. switch (o.getLastErrorCode()) {
  12455. case ErrorCode.NO_ERROR:
  12456. const e = o.getResponseJson();
  12457. C("Connection", "XHR received:", JSON.stringify(e)), i(e);
  12458. break;
  12459. case ErrorCode.TIMEOUT:
  12460. C("Connection", 'RPC "' + t + '" timed out'), r(new L(B.DEADLINE_EXCEEDED, "Request time out"));
  12461. break;
  12462. case ErrorCode.HTTP_ERROR:
  12463. const n = o.getStatus();
  12464. if (C("Connection", 'RPC "' + t + '" failed with status:', n, "response text:", o.getResponseText()),
  12465. n > 0) {
  12466. let t = o.getResponseJson();
  12467. Array.isArray(t) && (t = t[0]);
  12468. const e = null == t ? void 0 : t.error;
  12469. if (e && e.status && e.message) {
  12470. const t = function(t) {
  12471. const e = t.toLowerCase().replace(/_/g, "-");
  12472. return Object.values(B).indexOf(e) >= 0 ? e : B.UNKNOWN;
  12473. }(e.status);
  12474. r(new L(t, e.message));
  12475. } else r(new L(B.UNKNOWN, "Server responded with status " + o.getStatus()));
  12476. } else
  12477. // If we received an HTTP_ERROR but there's no status code,
  12478. // it's most probably a connection issue
  12479. r(new L(B.UNAVAILABLE, "Connection failed."));
  12480. break;
  12481. default:
  12482. O();
  12483. }
  12484. } finally {
  12485. C("Connection", 'RPC "' + t + '" completed.');
  12486. }
  12487. }));
  12488. const u = JSON.stringify(s);
  12489. o.send(e, "POST", u, n, 15);
  12490. }));
  12491. }
  12492. wo(t, e, n) {
  12493. const s = [ this.oo, "/", "google.firestore.v1.Firestore", "/", t, "/channel" ], i = createWebChannelTransport(), r = getStatEventTarget(), o = {
  12494. // Required for backend stickiness, routing behavior is based on this
  12495. // parameter.
  12496. httpSessionIdParam: "gsessionid",
  12497. initMessageHeaders: {},
  12498. messageUrlParams: {
  12499. // This param is used to improve routing and project isolation by the
  12500. // backend and must be included in every request.
  12501. database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`
  12502. },
  12503. sendRawJson: !0,
  12504. supportsCrossDomainXhr: !0,
  12505. internalChannelParams: {
  12506. // Override the default timeout (randomized between 10-20 seconds) since
  12507. // a large write batch on a slow internet connection may take a long
  12508. // time to send to the backend. Rather than have WebChannel impose a
  12509. // tight timeout which could lead to infinite timeouts and retries, we
  12510. // set it very large (5-10 minutes) and rely on the browser's builtin
  12511. // timeouts to kick in if the request isn't working.
  12512. forwardChannelRequestTimeoutMs: 6e5
  12513. },
  12514. forceLongPolling: this.forceLongPolling,
  12515. detectBufferingProxy: this.autoDetectLongPolling
  12516. };
  12517. this.useFetchStreams && (o.xmlHttpFactory = new FetchXmlHttpFactory({})), this.lo(o.initMessageHeaders, e, n),
  12518. // Sending the custom headers we just added to request.initMessageHeaders
  12519. // (Authorization, etc.) will trigger the browser to make a CORS preflight
  12520. // request because the XHR will no longer meet the criteria for a "simple"
  12521. // CORS request:
  12522. // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
  12523. // Therefore to avoid the CORS preflight request (an extra network
  12524. // roundtrip), we use the encodeInitMessageHeaders option to specify that
  12525. // the headers should instead be encoded in the request's POST payload,
  12526. // which is recognized by the webchannel backend.
  12527. o.encodeInitMessageHeaders = !0;
  12528. const u = s.join("");
  12529. C("Connection", "Creating WebChannel: " + u, o);
  12530. const c = i.createWebChannel(u, o);
  12531. // WebChannel supports sending the first message with the handshake - saving
  12532. // a network round trip. However, it will have to call send in the same
  12533. // JS event loop as open. In order to enforce this, we delay actually
  12534. // opening the WebChannel until send is called. Whether we have called
  12535. // open is tracked with this variable.
  12536. let a = !1, h = !1;
  12537. // A flag to determine whether the stream was closed (by us or through an
  12538. // error/close event) to avoid delivering multiple close events or sending
  12539. // on a closed stream
  12540. const l = new wu({
  12541. Hr: t => {
  12542. h ? C("Connection", "Not sending because WebChannel is closed:", t) : (a || (C("Connection", "Opening WebChannel transport."),
  12543. c.open(), a = !0), C("Connection", "WebChannel sending:", t), c.send(t));
  12544. },
  12545. Jr: () => c.close()
  12546. }), f = (t, e, n) => {
  12547. // TODO(dimond): closure typing seems broken because WebChannel does
  12548. // not implement goog.events.Listenable
  12549. t.listen(e, (t => {
  12550. try {
  12551. n(t);
  12552. } catch (t) {
  12553. setTimeout((() => {
  12554. throw t;
  12555. }), 0);
  12556. }
  12557. }));
  12558. };
  12559. // Closure events are guarded and exceptions are swallowed, so catch any
  12560. // exception and rethrow using a setTimeout so they become visible again.
  12561. // Note that eventually this function could go away if we are confident
  12562. // enough the code is exception free.
  12563. return f(c, WebChannel.EventType.OPEN, (() => {
  12564. h || C("Connection", "WebChannel transport opened.");
  12565. })), f(c, WebChannel.EventType.CLOSE, (() => {
  12566. h || (h = !0, C("Connection", "WebChannel transport closed"), l.io());
  12567. })), f(c, WebChannel.EventType.ERROR, (t => {
  12568. h || (h = !0, N("Connection", "WebChannel transport errored:", t), l.io(new L(B.UNAVAILABLE, "The operation could not be completed")));
  12569. })), f(c, WebChannel.EventType.MESSAGE, (t => {
  12570. var e;
  12571. if (!h) {
  12572. const n = t.data[0];
  12573. M(!!n);
  12574. // TODO(b/35143891): There is a bug in One Platform that caused errors
  12575. // (and only errors) to be wrapped in an extra array. To be forward
  12576. // compatible with the bug we need to check either condition. The latter
  12577. // can be removed once the fix has been rolled out.
  12578. // Use any because msgData.error is not typed.
  12579. const s = n, i = s.error || (null === (e = s[0]) || void 0 === e ? void 0 : e.error);
  12580. if (i) {
  12581. C("Connection", "WebChannel received error:", i);
  12582. // error.status will be a string like 'OK' or 'NOT_FOUND'.
  12583. const t = i.status;
  12584. let e =
  12585. /**
  12586. * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.
  12587. *
  12588. * @returns The Code equivalent to the given status string or undefined if
  12589. * there is no match.
  12590. */
  12591. function(t) {
  12592. // lookup by string
  12593. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12594. const e = us[t];
  12595. if (void 0 !== e) return hs(e);
  12596. }(t), n = i.message;
  12597. void 0 === e && (e = B.INTERNAL, n = "Unknown error status: " + t + " with message " + i.message),
  12598. // Mark closed so no further events are propagated
  12599. h = !0, l.io(new L(e, n)), c.close();
  12600. } else C("Connection", "WebChannel received:", n), l.ro(n);
  12601. }
  12602. })), f(r, Event.STAT_EVENT, (t => {
  12603. t.stat === Stat.PROXY ? C("Connection", "Detected buffering proxy") : t.stat === Stat.NOPROXY && C("Connection", "Detected no buffering proxy");
  12604. })), setTimeout((() => {
  12605. // Technically we could/should wait for the WebChannel opened event,
  12606. // but because we want to send the first message with the WebChannel
  12607. // handshake we pretend the channel opened here (asynchronously), and
  12608. // then delay the actual open until the first message is sent.
  12609. l.so();
  12610. }), 0), l;
  12611. }
  12612. }
  12613. /**
  12614. * @license
  12615. * Copyright 2020 Google LLC
  12616. *
  12617. * Licensed under the Apache License, Version 2.0 (the "License");
  12618. * you may not use this file except in compliance with the License.
  12619. * You may obtain a copy of the License at
  12620. *
  12621. * http://www.apache.org/licenses/LICENSE-2.0
  12622. *
  12623. * Unless required by applicable law or agreed to in writing, software
  12624. * distributed under the License is distributed on an "AS IS" BASIS,
  12625. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12626. * See the License for the specific language governing permissions and
  12627. * limitations under the License.
  12628. */
  12629. /** Initializes the WebChannelConnection for the browser. */
  12630. /**
  12631. * @license
  12632. * Copyright 2020 Google LLC
  12633. *
  12634. * Licensed under the Apache License, Version 2.0 (the "License");
  12635. * you may not use this file except in compliance with the License.
  12636. * You may obtain a copy of the License at
  12637. *
  12638. * http://www.apache.org/licenses/LICENSE-2.0
  12639. *
  12640. * Unless required by applicable law or agreed to in writing, software
  12641. * distributed under the License is distributed on an "AS IS" BASIS,
  12642. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12643. * See the License for the specific language governing permissions and
  12644. * limitations under the License.
  12645. */
  12646. /** The Platform's 'window' implementation or null if not available. */
  12647. function gu() {
  12648. // `window` is not always available, e.g. in ReactNative and WebWorkers.
  12649. // eslint-disable-next-line no-restricted-globals
  12650. return "undefined" != typeof window ? window : null;
  12651. }
  12652. /** The Platform's 'document' implementation or null if not available. */ function yu() {
  12653. // `document` is not always available, e.g. in ReactNative and WebWorkers.
  12654. // eslint-disable-next-line no-restricted-globals
  12655. return "undefined" != typeof document ? document : null;
  12656. }
  12657. /**
  12658. * @license
  12659. * Copyright 2020 Google LLC
  12660. *
  12661. * Licensed under the Apache License, Version 2.0 (the "License");
  12662. * you may not use this file except in compliance with the License.
  12663. * You may obtain a copy of the License at
  12664. *
  12665. * http://www.apache.org/licenses/LICENSE-2.0
  12666. *
  12667. * Unless required by applicable law or agreed to in writing, software
  12668. * distributed under the License is distributed on an "AS IS" BASIS,
  12669. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12670. * See the License for the specific language governing permissions and
  12671. * limitations under the License.
  12672. */ function pu(t) {
  12673. return new Fs(t, /* useProto3Json= */ !0);
  12674. }
  12675. /**
  12676. * An instance of the Platform's 'TextEncoder' implementation.
  12677. */
  12678. /**
  12679. * A helper for running delayed tasks following an exponential backoff curve
  12680. * between attempts.
  12681. *
  12682. * Each delay is made up of a "base" delay which follows the exponential
  12683. * backoff curve, and a +/- 50% "jitter" that is calculated and added to the
  12684. * base delay. This prevents clients from accidentally synchronizing their
  12685. * delays causing spikes of load to the backend.
  12686. */
  12687. class Iu {
  12688. constructor(
  12689. /**
  12690. * The AsyncQueue to run backoff operations on.
  12691. */
  12692. t,
  12693. /**
  12694. * The ID to use when scheduling backoff operations on the AsyncQueue.
  12695. */
  12696. e,
  12697. /**
  12698. * The initial delay (used as the base delay on the first retry attempt).
  12699. * Note that jitter will still be applied, so the actual delay could be as
  12700. * little as 0.5*initialDelayMs.
  12701. */
  12702. n = 1e3
  12703. /**
  12704. * The multiplier to use to determine the extended base delay after each
  12705. * attempt.
  12706. */ , s = 1.5
  12707. /**
  12708. * The maximum base delay after which no further backoff is performed.
  12709. * Note that jitter will still be applied, so the actual delay could be as
  12710. * much as 1.5*maxDelayMs.
  12711. */ , i = 6e4) {
  12712. this.Hs = t, this.timerId = e, this.mo = n, this.yo = s, this.po = i, this.Io = 0,
  12713. this.To = null,
  12714. /** The last backoff attempt, as epoch milliseconds. */
  12715. this.Eo = Date.now(), this.reset();
  12716. }
  12717. /**
  12718. * Resets the backoff delay.
  12719. *
  12720. * The very next backoffAndWait() will have no delay. If it is called again
  12721. * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
  12722. * subsequent ones will increase according to the backoffFactor.
  12723. */ reset() {
  12724. this.Io = 0;
  12725. }
  12726. /**
  12727. * Resets the backoff delay to the maximum delay (e.g. for use after a
  12728. * RESOURCE_EXHAUSTED error).
  12729. */ Ao() {
  12730. this.Io = this.po;
  12731. }
  12732. /**
  12733. * Returns a promise that resolves after currentDelayMs, and increases the
  12734. * delay for any subsequent attempts. If there was a pending backoff operation
  12735. * already, it will be canceled.
  12736. */ Ro(t) {
  12737. // Cancel any pending backoff operation.
  12738. this.cancel();
  12739. // First schedule using the current base (which may be 0 and should be
  12740. // honored as such).
  12741. const e = Math.floor(this.Io + this.bo()), n = Math.max(0, Date.now() - this.Eo), s = Math.max(0, e - n);
  12742. // Guard against lastAttemptTime being in the future due to a clock change.
  12743. s > 0 && C("ExponentialBackoff", `Backing off for ${s} ms (base delay: ${this.Io} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`),
  12744. this.To = this.Hs.enqueueAfterDelay(this.timerId, s, (() => (this.Eo = Date.now(),
  12745. t()))),
  12746. // Apply backoff factor to determine next delay and ensure it is within
  12747. // bounds.
  12748. this.Io *= this.yo, this.Io < this.mo && (this.Io = this.mo), this.Io > this.po && (this.Io = this.po);
  12749. }
  12750. Po() {
  12751. null !== this.To && (this.To.skipDelay(), this.To = null);
  12752. }
  12753. cancel() {
  12754. null !== this.To && (this.To.cancel(), this.To = null);
  12755. }
  12756. /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ bo() {
  12757. return (Math.random() - .5) * this.Io;
  12758. }
  12759. }
  12760. /**
  12761. * @license
  12762. * Copyright 2017 Google LLC
  12763. *
  12764. * Licensed under the Apache License, Version 2.0 (the "License");
  12765. * you may not use this file except in compliance with the License.
  12766. * You may obtain a copy of the License at
  12767. *
  12768. * http://www.apache.org/licenses/LICENSE-2.0
  12769. *
  12770. * Unless required by applicable law or agreed to in writing, software
  12771. * distributed under the License is distributed on an "AS IS" BASIS,
  12772. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12773. * See the License for the specific language governing permissions and
  12774. * limitations under the License.
  12775. */
  12776. /**
  12777. * A PersistentStream is an abstract base class that represents a streaming RPC
  12778. * to the Firestore backend. It's built on top of the connections own support
  12779. * for streaming RPCs, and adds several critical features for our clients:
  12780. *
  12781. * - Exponential backoff on failure
  12782. * - Authentication via CredentialsProvider
  12783. * - Dispatching all callbacks into the shared worker queue
  12784. * - Closing idle streams after 60 seconds of inactivity
  12785. *
  12786. * Subclasses of PersistentStream implement serialization of models to and
  12787. * from the JSON representation of the protocol buffers for a specific
  12788. * streaming RPC.
  12789. *
  12790. * ## Starting and Stopping
  12791. *
  12792. * Streaming RPCs are stateful and need to be start()ed before messages can
  12793. * be sent and received. The PersistentStream will call the onOpen() function
  12794. * of the listener once the stream is ready to accept requests.
  12795. *
  12796. * Should a start() fail, PersistentStream will call the registered onClose()
  12797. * listener with a FirestoreError indicating what went wrong.
  12798. *
  12799. * A PersistentStream can be started and stopped repeatedly.
  12800. *
  12801. * Generic types:
  12802. * SendType: The type of the outgoing message of the underlying
  12803. * connection stream
  12804. * ReceiveType: The type of the incoming message of the underlying
  12805. * connection stream
  12806. * ListenerType: The type of the listener that will be used for callbacks
  12807. */
  12808. class Tu {
  12809. constructor(t, e, n, s, i, r, o, u) {
  12810. this.Hs = t, this.vo = n, this.Vo = s, this.connection = i, this.authCredentialsProvider = r,
  12811. this.appCheckCredentialsProvider = o, this.listener = u, this.state = 0 /* PersistentStreamState.Initial */ ,
  12812. /**
  12813. * A close count that's incremented every time the stream is closed; used by
  12814. * getCloseGuardedDispatcher() to invalidate callbacks that happen after
  12815. * close.
  12816. */
  12817. this.So = 0, this.Do = null, this.Co = null, this.stream = null, this.xo = new Iu(t, e);
  12818. }
  12819. /**
  12820. * Returns true if start() has been called and no error has occurred. True
  12821. * indicates the stream is open or in the process of opening (which
  12822. * encompasses respecting backoff, getting auth tokens, and starting the
  12823. * actual RPC). Use isOpen() to determine if the stream is open and ready for
  12824. * outbound requests.
  12825. */ No() {
  12826. return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.ko();
  12827. }
  12828. /**
  12829. * Returns true if the underlying RPC is open (the onOpen() listener has been
  12830. * called) and the stream is ready for outbound requests.
  12831. */ ko() {
  12832. return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state;
  12833. }
  12834. /**
  12835. * Starts the RPC. Only allowed if isStarted() returns false. The stream is
  12836. * not immediately ready for use: onOpen() will be invoked when the RPC is
  12837. * ready for outbound requests, at which point isOpen() will return true.
  12838. *
  12839. * When start returns, isStarted() will return true.
  12840. */ start() {
  12841. 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.Oo();
  12842. }
  12843. /**
  12844. * Stops the RPC. This call is idempotent and allowed regardless of the
  12845. * current isStarted() state.
  12846. *
  12847. * When stop returns, isStarted() and isOpen() will both return false.
  12848. */ async stop() {
  12849. this.No() && await this.close(0 /* PersistentStreamState.Initial */);
  12850. }
  12851. /**
  12852. * After an error the stream will usually back off on the next attempt to
  12853. * start it. If the error warrants an immediate restart of the stream, the
  12854. * sender can use this to indicate that the receiver should not back off.
  12855. *
  12856. * Each error will call the onClose() listener. That function can decide to
  12857. * inhibit backoff if required.
  12858. */ Mo() {
  12859. this.state = 0 /* PersistentStreamState.Initial */ , this.xo.reset();
  12860. }
  12861. /**
  12862. * Marks this stream as idle. If no further actions are performed on the
  12863. * stream for one minute, the stream will automatically close itself and
  12864. * notify the stream's onClose() handler with Status.OK. The stream will then
  12865. * be in a !isStarted() state, requiring the caller to start the stream again
  12866. * before further use.
  12867. *
  12868. * Only streams that are in state 'Open' can be marked idle, as all other
  12869. * states imply pending network operations.
  12870. */ Fo() {
  12871. // Starts the idle time if we are in state 'Open' and are not yet already
  12872. // running a timer (in which case the previous idle timeout still applies).
  12873. this.ko() && null === this.Do && (this.Do = this.Hs.enqueueAfterDelay(this.vo, 6e4, (() => this.$o())));
  12874. }
  12875. /** Sends a message to the underlying stream. */ Bo(t) {
  12876. this.Lo(), this.stream.send(t);
  12877. }
  12878. /** Called by the idle timer when the stream should close due to inactivity. */ async $o() {
  12879. if (this.ko())
  12880. // When timing out an idle stream there's no reason to force the stream into backoff when
  12881. // it restarts so set the stream state to Initial instead of Error.
  12882. return this.close(0 /* PersistentStreamState.Initial */);
  12883. }
  12884. /** Marks the stream as active again. */ Lo() {
  12885. this.Do && (this.Do.cancel(), this.Do = null);
  12886. }
  12887. /** Cancels the health check delayed operation. */ qo() {
  12888. this.Co && (this.Co.cancel(), this.Co = null);
  12889. }
  12890. /**
  12891. * Closes the stream and cleans up as necessary:
  12892. *
  12893. * * closes the underlying GRPC stream;
  12894. * * calls the onClose handler with the given 'error';
  12895. * * sets internal stream state to 'finalState';
  12896. * * adjusts the backoff timer based on the error
  12897. *
  12898. * A new stream can be opened by calling start().
  12899. *
  12900. * @param finalState - the intended state of the stream after closing.
  12901. * @param error - the error the connection was closed with.
  12902. */ async close(t, e) {
  12903. // Cancel any outstanding timers (they're guaranteed not to execute).
  12904. this.Lo(), this.qo(), this.xo.cancel(),
  12905. // Invalidates any stream-related callbacks (e.g. from auth or the
  12906. // underlying stream), guaranteeing they won't execute.
  12907. this.So++, 4 /* PersistentStreamState.Error */ !== t ?
  12908. // If this is an intentional close ensure we don't delay our next connection attempt.
  12909. this.xo.reset() : e && e.code === B.RESOURCE_EXHAUSTED ? (
  12910. // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)
  12911. x(e.toString()), x("Using maximum backoff delay to prevent overloading the backend."),
  12912. this.xo.Ao()) : e && e.code === B.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && (
  12913. // "unauthenticated" error means the token was rejected. This should rarely
  12914. // happen since both Auth and AppCheck ensure a sufficient TTL when we
  12915. // request a token. If a user manually resets their system clock this can
  12916. // fail, however. In this case, we should get a Code.UNAUTHENTICATED error
  12917. // before we received the first message and we need to invalidate the token
  12918. // to ensure that we fetch a new token.
  12919. this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()),
  12920. // Clean up the underlying stream because we are no longer interested in events.
  12921. null !== this.stream && (this.Uo(), this.stream.close(), this.stream = null),
  12922. // This state must be assigned before calling onClose() to allow the callback to
  12923. // inhibit backoff or otherwise manipulate the state in its non-started state.
  12924. this.state = t,
  12925. // Notify the listener that the stream closed.
  12926. await this.listener.Zr(e);
  12927. }
  12928. /**
  12929. * Can be overridden to perform additional cleanup before the stream is closed.
  12930. * Calling super.tearDown() is not required.
  12931. */ Uo() {}
  12932. auth() {
  12933. this.state = 1 /* PersistentStreamState.Starting */;
  12934. const t = this.Ko(this.So), e = this.So;
  12935. // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.
  12936. Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([t, n]) => {
  12937. // Stream can be stopped while waiting for authentication.
  12938. // TODO(mikelehen): We really should just use dispatchIfNotClosed
  12939. // and let this dispatch onto the queue, but that opened a spec test can
  12940. // of worms that I don't want to deal with in this PR.
  12941. this.So === e &&
  12942. // Normally we'd have to schedule the callback on the AsyncQueue.
  12943. // However, the following calls are safe to be called outside the
  12944. // AsyncQueue since they don't chain asynchronous calls
  12945. this.Go(t, n);
  12946. }), (e => {
  12947. t((() => {
  12948. const t = new L(B.UNKNOWN, "Fetching auth token failed: " + e.message);
  12949. return this.Qo(t);
  12950. }));
  12951. }));
  12952. }
  12953. Go(t, e) {
  12954. const n = this.Ko(this.So);
  12955. this.stream = this.jo(t, e), this.stream.Yr((() => {
  12956. n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.Co = this.Hs.enqueueAfterDelay(this.Vo, 1e4, (() => (this.ko() && (this.state = 3 /* PersistentStreamState.Healthy */),
  12957. Promise.resolve()))), this.listener.Yr())));
  12958. })), this.stream.Zr((t => {
  12959. n((() => this.Qo(t)));
  12960. })), this.stream.onMessage((t => {
  12961. n((() => this.onMessage(t)));
  12962. }));
  12963. }
  12964. Oo() {
  12965. this.state = 5 /* PersistentStreamState.Backoff */ , this.xo.Ro((async () => {
  12966. this.state = 0 /* PersistentStreamState.Initial */ , this.start();
  12967. }));
  12968. }
  12969. // Visible for tests
  12970. Qo(t) {
  12971. // In theory the stream could close cleanly, however, in our current model
  12972. // we never expect this to happen because if we stop a stream ourselves,
  12973. // this callback will never be called. To prevent cases where we retry
  12974. // without a backoff accidentally, we set the stream to error in all cases.
  12975. return C("PersistentStream", `close with error: ${t}`), this.stream = null, this.close(4 /* PersistentStreamState.Error */ , t);
  12976. }
  12977. /**
  12978. * Returns a "dispatcher" function that dispatches operations onto the
  12979. * AsyncQueue but only runs them if closeCount remains unchanged. This allows
  12980. * us to turn auth / stream callbacks into no-ops if the stream is closed /
  12981. * re-opened, etc.
  12982. */ Ko(t) {
  12983. return e => {
  12984. this.Hs.enqueueAndForget((() => this.So === t ? e() : (C("PersistentStream", "stream callback skipped by getCloseGuardedDispatcher."),
  12985. Promise.resolve())));
  12986. };
  12987. }
  12988. }
  12989. /**
  12990. * A PersistentStream that implements the Listen RPC.
  12991. *
  12992. * Once the Listen stream has called the onOpen() listener, any number of
  12993. * listen() and unlisten() calls can be made to control what changes will be
  12994. * sent from the server for ListenResponses.
  12995. */ class Eu extends Tu {
  12996. constructor(t, e, n, s, i, r) {
  12997. super(t, "listen_stream_connection_backoff" /* TimerId.ListenStreamConnectionBackoff */ , "listen_stream_idle" /* TimerId.ListenStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , e, n, s, r),
  12998. this.yt = i;
  12999. }
  13000. jo(t, e) {
  13001. return this.connection.wo("Listen", t, e);
  13002. }
  13003. onMessage(t) {
  13004. // A successful response means the stream is healthy
  13005. this.xo.reset();
  13006. const e = Zs(this.yt, t), n = function(t) {
  13007. // We have only reached a consistent snapshot for the entire stream if there
  13008. // is a read_time set and it applies to all targets (i.e. the list of
  13009. // targets is empty). The backend is guaranteed to send such responses.
  13010. if (!("targetChange" in t)) return st.min();
  13011. const e = t.targetChange;
  13012. return e.targetIds && e.targetIds.length ? st.min() : e.readTime ? qs(e.readTime) : st.min();
  13013. }(t);
  13014. return this.listener.Wo(e, n);
  13015. }
  13016. /**
  13017. * Registers interest in the results of the given target. If the target
  13018. * includes a resumeToken it will be included in the request. Results that
  13019. * affect the target will be streamed back as WatchChange messages that
  13020. * reference the targetId.
  13021. */ zo(t) {
  13022. const e = {};
  13023. e.database = zs(this.yt), e.addTarget = function(t, e) {
  13024. let n;
  13025. const s = e.target;
  13026. return n = rn(s) ? {
  13027. documents: si(t, s)
  13028. } : {
  13029. query: ii(t, s)
  13030. }, n.targetId = e.targetId, e.resumeToken.approximateByteSize() > 0 ? n.resumeToken = Bs(t, e.resumeToken) : e.snapshotVersion.compareTo(st.min()) > 0 && (
  13031. // TODO(wuandy): Consider removing above check because it is most likely true.
  13032. // Right now, many tests depend on this behaviour though (leaving min() out
  13033. // of serialization).
  13034. n.readTime = $s(t, e.snapshotVersion.toTimestamp())), n;
  13035. }(this.yt, t);
  13036. const n = oi(this.yt, t);
  13037. n && (e.labels = n), this.Bo(e);
  13038. }
  13039. /**
  13040. * Unregisters interest in the results of the target associated with the
  13041. * given targetId.
  13042. */ Ho(t) {
  13043. const e = {};
  13044. e.database = zs(this.yt), e.removeTarget = t, this.Bo(e);
  13045. }
  13046. }
  13047. /**
  13048. * A Stream that implements the Write RPC.
  13049. *
  13050. * The Write RPC requires the caller to maintain special streamToken
  13051. * state in between calls, to help the server understand which responses the
  13052. * client has processed by the time the next request is made. Every response
  13053. * will contain a streamToken; this value must be passed to the next
  13054. * request.
  13055. *
  13056. * After calling start() on this stream, the next request must be a handshake,
  13057. * containing whatever streamToken is on hand. Once a response to this
  13058. * request is received, all pending mutations may be submitted. When
  13059. * submitting multiple batches of mutations at the same time, it's
  13060. * okay to use the same streamToken for the calls to writeMutations.
  13061. *
  13062. * TODO(b/33271235): Use proto types
  13063. */ class Au extends Tu {
  13064. constructor(t, e, n, s, i, r) {
  13065. super(t, "write_stream_connection_backoff" /* TimerId.WriteStreamConnectionBackoff */ , "write_stream_idle" /* TimerId.WriteStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , e, n, s, r),
  13066. this.yt = i, this.Jo = !1;
  13067. }
  13068. /**
  13069. * Tracks whether or not a handshake has been successfully exchanged and
  13070. * the stream is ready to accept mutations.
  13071. */ get Yo() {
  13072. return this.Jo;
  13073. }
  13074. // Override of PersistentStream.start
  13075. start() {
  13076. this.Jo = !1, this.lastStreamToken = void 0, super.start();
  13077. }
  13078. Uo() {
  13079. this.Jo && this.Xo([]);
  13080. }
  13081. jo(t, e) {
  13082. return this.connection.wo("Write", t, e);
  13083. }
  13084. onMessage(t) {
  13085. if (
  13086. // Always capture the last stream token.
  13087. M(!!t.streamToken), this.lastStreamToken = t.streamToken, this.Jo) {
  13088. // A successful first write response means the stream is healthy,
  13089. // Note, that we could consider a successful handshake healthy, however,
  13090. // the write itself might be causing an error we want to back off from.
  13091. this.xo.reset();
  13092. const e = ni(t.writeResults, t.commitTime), n = qs(t.commitTime);
  13093. return this.listener.Zo(n, e);
  13094. }
  13095. // The first response is always the handshake response
  13096. return M(!t.writeResults || 0 === t.writeResults.length), this.Jo = !0, this.listener.tu();
  13097. }
  13098. /**
  13099. * Sends an initial streamToken to the server, performing the handshake
  13100. * required to make the StreamingWrite RPC work. Subsequent
  13101. * calls should wait until onHandshakeComplete was called.
  13102. */ eu() {
  13103. // TODO(dimond): Support stream resumption. We intentionally do not set the
  13104. // stream token on the handshake, ignoring any stream token we might have.
  13105. const t = {};
  13106. t.database = zs(this.yt), this.Bo(t);
  13107. }
  13108. /** Sends a group of mutations to the Firestore backend to apply. */ Xo(t) {
  13109. const e = {
  13110. streamToken: this.lastStreamToken,
  13111. writes: t.map((t => ti(this.yt, t)))
  13112. };
  13113. this.Bo(e);
  13114. }
  13115. }
  13116. /**
  13117. * @license
  13118. * Copyright 2017 Google LLC
  13119. *
  13120. * Licensed under the Apache License, Version 2.0 (the "License");
  13121. * you may not use this file except in compliance with the License.
  13122. * You may obtain a copy of the License at
  13123. *
  13124. * http://www.apache.org/licenses/LICENSE-2.0
  13125. *
  13126. * Unless required by applicable law or agreed to in writing, software
  13127. * distributed under the License is distributed on an "AS IS" BASIS,
  13128. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13129. * See the License for the specific language governing permissions and
  13130. * limitations under the License.
  13131. */
  13132. /**
  13133. * Datastore and its related methods are a wrapper around the external Google
  13134. * Cloud Datastore grpc API, which provides an interface that is more convenient
  13135. * for the rest of the client SDK architecture to consume.
  13136. */
  13137. /**
  13138. * An implementation of Datastore that exposes additional state for internal
  13139. * consumption.
  13140. */
  13141. class Ru extends class {} {
  13142. constructor(t, e, n, s) {
  13143. super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = n,
  13144. this.yt = s, this.nu = !1;
  13145. }
  13146. su() {
  13147. if (this.nu) throw new L(B.FAILED_PRECONDITION, "The client has already been terminated.");
  13148. }
  13149. /** Invokes the provided RPC with auth and AppCheck tokens. */ ao(t, e, n) {
  13150. return this.su(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, i]) => this.connection.ao(t, e, n, s, i))).catch((t => {
  13151. throw "FirebaseError" === t.name ? (t.code === B.UNAUTHENTICATED && (this.authCredentials.invalidateToken(),
  13152. this.appCheckCredentials.invalidateToken()), t) : new L(B.UNKNOWN, t.toString());
  13153. }));
  13154. }
  13155. /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ _o(t, e, n, s) {
  13156. return this.su(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, r]) => this.connection._o(t, e, n, i, r, s))).catch((t => {
  13157. throw "FirebaseError" === t.name ? (t.code === B.UNAUTHENTICATED && (this.authCredentials.invalidateToken(),
  13158. this.appCheckCredentials.invalidateToken()), t) : new L(B.UNKNOWN, t.toString());
  13159. }));
  13160. }
  13161. terminate() {
  13162. this.nu = !0;
  13163. }
  13164. }
  13165. // TODO(firestorexp): Make sure there is only one Datastore instance per
  13166. // firestore-exp client.
  13167. async function bu(t, e) {
  13168. const n = $(t), s = function(t, e) {
  13169. const n = ii(t, e);
  13170. return {
  13171. structuredAggregationQuery: {
  13172. aggregations: [ {
  13173. count: {},
  13174. alias: "count_alias"
  13175. } ],
  13176. structuredQuery: n.structuredQuery
  13177. },
  13178. parent: n.parent
  13179. };
  13180. }(n.yt, gn(e)), i = s.parent;
  13181. n.connection.co || delete s.parent;
  13182. return (await n._o("RunAggregationQuery", i, s, /*expectedResponseCount=*/ 1)).filter((t => !!t.result)).map((t => t.result.aggregateFields));
  13183. }
  13184. /**
  13185. * A component used by the RemoteStore to track the OnlineState (that is,
  13186. * whether or not the client as a whole should be considered to be online or
  13187. * offline), implementing the appropriate heuristics.
  13188. *
  13189. * In particular, when the client is trying to connect to the backend, we
  13190. * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for
  13191. * a connection to succeed. If we have too many failures or the timeout elapses,
  13192. * then we set the OnlineState to Offline, and the client will behave as if
  13193. * it is offline (get()s will return cached data, etc.).
  13194. */
  13195. class Pu {
  13196. constructor(t, e) {
  13197. this.asyncQueue = t, this.onlineStateHandler = e,
  13198. /** The current OnlineState. */
  13199. this.state = "Unknown" /* OnlineState.Unknown */ ,
  13200. /**
  13201. * A count of consecutive failures to open the stream. If it reaches the
  13202. * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to
  13203. * Offline.
  13204. */
  13205. this.iu = 0,
  13206. /**
  13207. * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we
  13208. * transition from OnlineState.Unknown to OnlineState.Offline without waiting
  13209. * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).
  13210. */
  13211. this.ru = null,
  13212. /**
  13213. * Whether the client should log a warning message if it fails to connect to
  13214. * the backend (initially true, cleared after a successful stream, or if we've
  13215. * logged the message already).
  13216. */
  13217. this.ou = !0;
  13218. }
  13219. /**
  13220. * Called by RemoteStore when a watch stream is started (including on each
  13221. * backoff attempt).
  13222. *
  13223. * If this is the first attempt, it sets the OnlineState to Unknown and starts
  13224. * the onlineStateTimer.
  13225. */ uu() {
  13226. 0 === this.iu && (this.cu("Unknown" /* OnlineState.Unknown */), this.ru = this.asyncQueue.enqueueAfterDelay("online_state_timeout" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this.ru = null,
  13227. this.au("Backend didn't respond within 10 seconds."), this.cu("Offline" /* OnlineState.Offline */),
  13228. Promise.resolve()))));
  13229. }
  13230. /**
  13231. * Updates our OnlineState as appropriate after the watch stream reports a
  13232. * failure. The first failure moves us to the 'Unknown' state. We then may
  13233. * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we
  13234. * actually transition to the 'Offline' state.
  13235. */ hu(t) {
  13236. "Online" /* OnlineState.Online */ === this.state ? this.cu("Unknown" /* OnlineState.Unknown */) : (this.iu++,
  13237. this.iu >= 1 && (this.lu(), this.au(`Connection failed 1 times. Most recent error: ${t.toString()}`),
  13238. this.cu("Offline" /* OnlineState.Offline */)));
  13239. }
  13240. /**
  13241. * Explicitly sets the OnlineState to the specified state.
  13242. *
  13243. * Note that this resets our timers / failure counters, etc. used by our
  13244. * Offline heuristics, so must not be used in place of
  13245. * handleWatchStreamStart() and handleWatchStreamFailure().
  13246. */ set(t) {
  13247. this.lu(), this.iu = 0, "Online" /* OnlineState.Online */ === t && (
  13248. // We've connected to watch at least once. Don't warn the developer
  13249. // about being offline going forward.
  13250. this.ou = !1), this.cu(t);
  13251. }
  13252. cu(t) {
  13253. t !== this.state && (this.state = t, this.onlineStateHandler(t));
  13254. }
  13255. au(t) {
  13256. const e = `Could not reach Cloud Firestore backend. ${t}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;
  13257. this.ou ? (x(e), this.ou = !1) : C("OnlineStateTracker", e);
  13258. }
  13259. lu() {
  13260. null !== this.ru && (this.ru.cancel(), this.ru = null);
  13261. }
  13262. }
  13263. /**
  13264. * @license
  13265. * Copyright 2017 Google LLC
  13266. *
  13267. * Licensed under the Apache License, Version 2.0 (the "License");
  13268. * you may not use this file except in compliance with the License.
  13269. * You may obtain a copy of the License at
  13270. *
  13271. * http://www.apache.org/licenses/LICENSE-2.0
  13272. *
  13273. * Unless required by applicable law or agreed to in writing, software
  13274. * distributed under the License is distributed on an "AS IS" BASIS,
  13275. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13276. * See the License for the specific language governing permissions and
  13277. * limitations under the License.
  13278. */ class vu {
  13279. constructor(
  13280. /**
  13281. * The local store, used to fill the write pipeline with outbound mutations.
  13282. */
  13283. t,
  13284. /** The client-side proxy for interacting with the backend. */
  13285. e, n, s, i) {
  13286. this.localStore = t, this.datastore = e, this.asyncQueue = n, this.remoteSyncer = {},
  13287. /**
  13288. * A list of up to MAX_PENDING_WRITES writes that we have fetched from the
  13289. * LocalStore via fillWritePipeline() and have or will send to the write
  13290. * stream.
  13291. *
  13292. * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or
  13293. * restart the write stream. When the stream is established the writes in the
  13294. * pipeline will be sent in order.
  13295. *
  13296. * Writes remain in writePipeline until they are acknowledged by the backend
  13297. * and thus will automatically be re-sent if the stream is interrupted /
  13298. * restarted before they're acknowledged.
  13299. *
  13300. * Write responses from the backend are linked to their originating request
  13301. * purely based on order, and so we can just shift() writes from the front of
  13302. * the writePipeline as we receive responses.
  13303. */
  13304. this.fu = [],
  13305. /**
  13306. * A mapping of watched targets that the client cares about tracking and the
  13307. * user has explicitly called a 'listen' for this target.
  13308. *
  13309. * These targets may or may not have been sent to or acknowledged by the
  13310. * server. On re-establishing the listen stream, these targets should be sent
  13311. * to the server. The targets removed with unlistens are removed eagerly
  13312. * without waiting for confirmation from the listen stream.
  13313. */
  13314. this.du = new Map,
  13315. /**
  13316. * A set of reasons for why the RemoteStore may be offline. If empty, the
  13317. * RemoteStore may start its network connections.
  13318. */
  13319. this._u = new Set,
  13320. /**
  13321. * Event handlers that get called when the network is disabled or enabled.
  13322. *
  13323. * PORTING NOTE: These functions are used on the Web client to create the
  13324. * underlying streams (to support tree-shakeable streams). On Android and iOS,
  13325. * the streams are created during construction of RemoteStore.
  13326. */
  13327. this.wu = [], this.mu = i, this.mu.Ur((t => {
  13328. n.enqueueAndForget((async () => {
  13329. // Porting Note: Unlike iOS, `restartNetwork()` is called even when the
  13330. // network becomes unreachable as we don't have any other way to tear
  13331. // down our streams.
  13332. Mu(this) && (C("RemoteStore", "Restarting streams for network reachability change."),
  13333. await async function(t) {
  13334. const e = $(t);
  13335. e._u.add(4 /* OfflineCause.ConnectivityChange */), await Su(e), e.gu.set("Unknown" /* OnlineState.Unknown */),
  13336. e._u.delete(4 /* OfflineCause.ConnectivityChange */), await Vu(e);
  13337. }(this));
  13338. }));
  13339. })), this.gu = new Pu(n, s);
  13340. }
  13341. }
  13342. async function Vu(t) {
  13343. if (Mu(t)) for (const e of t.wu) await e(/* enabled= */ !0);
  13344. }
  13345. /**
  13346. * Temporarily disables the network. The network can be re-enabled using
  13347. * enableNetwork().
  13348. */ async function Su(t) {
  13349. for (const e of t.wu) await e(/* enabled= */ !1);
  13350. }
  13351. /**
  13352. * Starts new listen for the given target. Uses resume token if provided. It
  13353. * is a no-op if the target of given `TargetData` is already being listened to.
  13354. */
  13355. function Du(t, e) {
  13356. const n = $(t);
  13357. n.du.has(e.targetId) || (
  13358. // Mark this as something the client is currently listening for.
  13359. n.du.set(e.targetId, e), Ou(n) ?
  13360. // The listen will be sent in onWatchStreamOpen
  13361. ku(n) : tc(n).ko() && xu(n, e));
  13362. }
  13363. /**
  13364. * Removes the listen from server. It is a no-op if the given target id is
  13365. * not being listened to.
  13366. */ function Cu(t, e) {
  13367. const n = $(t), s = tc(n);
  13368. n.du.delete(e), s.ko() && Nu(n, e), 0 === n.du.size && (s.ko() ? s.Fo() : Mu(n) &&
  13369. // Revert to OnlineState.Unknown if the watch stream is not open and we
  13370. // have no listeners, since without any listens to send we cannot
  13371. // confirm if the stream is healthy and upgrade to OnlineState.Online.
  13372. n.gu.set("Unknown" /* OnlineState.Unknown */));
  13373. }
  13374. /**
  13375. * We need to increment the the expected number of pending responses we're due
  13376. * from watch so we wait for the ack to process any messages from this target.
  13377. */ function xu(t, e) {
  13378. t.yu.Ot(e.targetId), tc(t).zo(e);
  13379. }
  13380. /**
  13381. * We need to increment the expected number of pending responses we're due
  13382. * from watch so we wait for the removal on the server before we process any
  13383. * messages from this target.
  13384. */ function Nu(t, e) {
  13385. t.yu.Ot(e), tc(t).Ho(e);
  13386. }
  13387. function ku(t) {
  13388. t.yu = new Cs({
  13389. getRemoteKeysForTarget: e => t.remoteSyncer.getRemoteKeysForTarget(e),
  13390. ne: e => t.du.get(e) || null
  13391. }), tc(t).start(), t.gu.uu();
  13392. }
  13393. /**
  13394. * Returns whether the watch stream should be started because it's necessary
  13395. * and has not yet been started.
  13396. */ function Ou(t) {
  13397. return Mu(t) && !tc(t).No() && t.du.size > 0;
  13398. }
  13399. function Mu(t) {
  13400. return 0 === $(t)._u.size;
  13401. }
  13402. function Fu(t) {
  13403. t.yu = void 0;
  13404. }
  13405. async function $u(t) {
  13406. t.du.forEach(((e, n) => {
  13407. xu(t, e);
  13408. }));
  13409. }
  13410. async function Bu(t, e) {
  13411. Fu(t),
  13412. // If we still need the watch stream, retry the connection.
  13413. Ou(t) ? (t.gu.hu(e), ku(t)) :
  13414. // No need to restart watch stream because there are no active targets.
  13415. // The online state is set to unknown because there is no active attempt
  13416. // at establishing a connection
  13417. t.gu.set("Unknown" /* OnlineState.Unknown */);
  13418. }
  13419. async function Lu(t, e, n) {
  13420. if (
  13421. // Mark the client as online since we got a message from the server
  13422. t.gu.set("Online" /* OnlineState.Online */), e instanceof Ss && 2 /* WatchTargetChangeState.Removed */ === e.state && e.cause)
  13423. // There was an error on a target, don't wait for a consistent snapshot
  13424. // to raise events
  13425. try {
  13426. await
  13427. /** Handles an error on a target */
  13428. async function(t, e) {
  13429. const n = e.cause;
  13430. for (const s of e.targetIds)
  13431. // A watched target might have been removed already.
  13432. t.du.has(s) && (await t.remoteSyncer.rejectListen(s, n), t.du.delete(s), t.yu.removeTarget(s));
  13433. }
  13434. /**
  13435. * Attempts to fill our write pipeline with writes from the LocalStore.
  13436. *
  13437. * Called internally to bootstrap or refill the write pipeline and by
  13438. * SyncEngine whenever there are new mutations to process.
  13439. *
  13440. * Starts the write stream if necessary.
  13441. */ (t, e);
  13442. } catch (n) {
  13443. C("RemoteStore", "Failed to remove targets %s: %s ", e.targetIds.join(","), n),
  13444. await qu(t, n);
  13445. } else if (e instanceof vs ? t.yu.Kt(e) : e instanceof Vs ? t.yu.Jt(e) : t.yu.jt(e),
  13446. !n.isEqual(st.min())) try {
  13447. const e = await Go(t.localStore);
  13448. n.compareTo(e) >= 0 &&
  13449. // We have received a target change with a global snapshot if the snapshot
  13450. // version is not equal to SnapshotVersion.min().
  13451. await
  13452. /**
  13453. * Takes a batch of changes from the Datastore, repackages them as a
  13454. * RemoteEvent, and passes that on to the listener, which is typically the
  13455. * SyncEngine.
  13456. */
  13457. function(t, e) {
  13458. const n = t.yu.Zt(e);
  13459. // Update in-memory resume tokens. LocalStore will update the
  13460. // persistent view of these when applying the completed RemoteEvent.
  13461. return n.targetChanges.forEach(((n, s) => {
  13462. if (n.resumeToken.approximateByteSize() > 0) {
  13463. const i = t.du.get(s);
  13464. // A watched target might have been removed already.
  13465. i && t.du.set(s, i.withResumeToken(n.resumeToken, e));
  13466. }
  13467. })),
  13468. // Re-establish listens for the targets that have been invalidated by
  13469. // existence filter mismatches.
  13470. n.targetMismatches.forEach((e => {
  13471. const n = t.du.get(e);
  13472. if (!n)
  13473. // A watched target might have been removed already.
  13474. return;
  13475. // Clear the resume token for the target, since we're in a known mismatch
  13476. // state.
  13477. t.du.set(e, n.withResumeToken(Qt.EMPTY_BYTE_STRING, n.snapshotVersion)),
  13478. // Cause a hard reset by unwatching and rewatching immediately, but
  13479. // deliberately don't send a resume token so that we get a full update.
  13480. Nu(t, e);
  13481. // Mark the target we send as being on behalf of an existence filter
  13482. // mismatch, but don't actually retain that in listenTargets. This ensures
  13483. // that we flag the first re-listen this way without impacting future
  13484. // listens of this target (that might happen e.g. on reconnect).
  13485. const s = new zi(n.target, e, 1 /* TargetPurpose.ExistenceFilterMismatch */ , n.sequenceNumber);
  13486. xu(t, s);
  13487. })), t.remoteSyncer.applyRemoteEvent(n);
  13488. }(t, n);
  13489. } catch (e) {
  13490. C("RemoteStore", "Failed to raise snapshot:", e), await qu(t, e);
  13491. }
  13492. }
  13493. /**
  13494. * Recovery logic for IndexedDB errors that takes the network offline until
  13495. * `op` succeeds. Retries are scheduled with backoff using
  13496. * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is
  13497. * validated via a generic operation.
  13498. *
  13499. * The returned Promise is resolved once the network is disabled and before
  13500. * any retry attempt.
  13501. */ async function qu(t, e, n) {
  13502. if (!Vt(e)) throw e;
  13503. t._u.add(1 /* OfflineCause.IndexedDbFailed */),
  13504. // Disable network and raise offline snapshots
  13505. await Su(t), t.gu.set("Offline" /* OnlineState.Offline */), n || (
  13506. // Use a simple read operation to determine if IndexedDB recovered.
  13507. // Ideally, we would expose a health check directly on SimpleDb, but
  13508. // RemoteStore only has access to persistence through LocalStore.
  13509. n = () => Go(t.localStore)),
  13510. // Probe IndexedDB periodically and re-enable network
  13511. t.asyncQueue.enqueueRetryable((async () => {
  13512. C("RemoteStore", "Retrying IndexedDB access"), await n(), t._u.delete(1 /* OfflineCause.IndexedDbFailed */),
  13513. await Vu(t);
  13514. }));
  13515. }
  13516. /**
  13517. * Executes `op`. If `op` fails, takes the network offline until `op`
  13518. * succeeds. Returns after the first attempt.
  13519. */ function Uu(t, e) {
  13520. return e().catch((n => qu(t, n, e)));
  13521. }
  13522. async function Ku(t) {
  13523. const e = $(t), n = ec(e);
  13524. let s = e.fu.length > 0 ? e.fu[e.fu.length - 1].batchId : -1;
  13525. for (;Gu(e); ) try {
  13526. const t = await Wo(e.localStore, s);
  13527. if (null === t) {
  13528. 0 === e.fu.length && n.Fo();
  13529. break;
  13530. }
  13531. s = t.batchId, Qu(e, t);
  13532. } catch (t) {
  13533. await qu(e, t);
  13534. }
  13535. ju(e) && Wu(e);
  13536. }
  13537. /**
  13538. * Returns true if we can add to the write pipeline (i.e. the network is
  13539. * enabled and the write pipeline is not full).
  13540. */ function Gu(t) {
  13541. return Mu(t) && t.fu.length < 10;
  13542. }
  13543. /**
  13544. * Queues additional writes to be sent to the write stream, sending them
  13545. * immediately if the write stream is established.
  13546. */ function Qu(t, e) {
  13547. t.fu.push(e);
  13548. const n = ec(t);
  13549. n.ko() && n.Yo && n.Xo(e.mutations);
  13550. }
  13551. function ju(t) {
  13552. return Mu(t) && !ec(t).No() && t.fu.length > 0;
  13553. }
  13554. function Wu(t) {
  13555. ec(t).start();
  13556. }
  13557. async function zu(t) {
  13558. ec(t).eu();
  13559. }
  13560. async function Hu(t) {
  13561. const e = ec(t);
  13562. // Send the write pipeline now that the stream is established.
  13563. for (const n of t.fu) e.Xo(n.mutations);
  13564. }
  13565. async function Ju(t, e, n) {
  13566. const s = t.fu.shift(), i = ji.from(s, e, n);
  13567. await Uu(t, (() => t.remoteSyncer.applySuccessfulWrite(i))),
  13568. // It's possible that with the completion of this mutation another
  13569. // slot has freed up.
  13570. await Ku(t);
  13571. }
  13572. async function Yu(t, e) {
  13573. // If the write stream closed after the write handshake completes, a write
  13574. // operation failed and we fail the pending operation.
  13575. e && ec(t).Yo &&
  13576. // This error affects the actual write.
  13577. await async function(t, e) {
  13578. // Only handle permanent errors here. If it's transient, just let the retry
  13579. // logic kick in.
  13580. if (n = e.code, as(n) && n !== B.ABORTED) {
  13581. // This was a permanent error, the request itself was the problem
  13582. // so it's not going to succeed if we resend it.
  13583. const n = t.fu.shift();
  13584. // In this case it's also unlikely that the server itself is melting
  13585. // down -- this was just a bad request so inhibit backoff on the next
  13586. // restart.
  13587. ec(t).Mo(), await Uu(t, (() => t.remoteSyncer.rejectFailedWrite(n.batchId, e))),
  13588. // It's possible that with the completion of this mutation
  13589. // another slot has freed up.
  13590. await Ku(t);
  13591. }
  13592. var n;
  13593. }(t, e),
  13594. // The write stream might have been started by refilling the write
  13595. // pipeline for failed writes
  13596. ju(t) && Wu(t);
  13597. }
  13598. async function Xu(t, e) {
  13599. const n = $(t);
  13600. n.asyncQueue.verifyOperationInProgress(), C("RemoteStore", "RemoteStore received new credentials");
  13601. const s = Mu(n);
  13602. // Tear down and re-create our network streams. This will ensure we get a
  13603. // fresh auth token for the new user and re-fill the write pipeline with
  13604. // new mutations from the LocalStore (since mutations are per-user).
  13605. n._u.add(3 /* OfflineCause.CredentialChange */), await Su(n), s &&
  13606. // Don't set the network status to Unknown if we are offline.
  13607. n.gu.set("Unknown" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(e),
  13608. n._u.delete(3 /* OfflineCause.CredentialChange */), await Vu(n);
  13609. }
  13610. /**
  13611. * Toggles the network state when the client gains or loses its primary lease.
  13612. */ async function Zu(t, e) {
  13613. const n = $(t);
  13614. e ? (n._u.delete(2 /* OfflineCause.IsSecondary */), await Vu(n)) : e || (n._u.add(2 /* OfflineCause.IsSecondary */),
  13615. await Su(n), n.gu.set("Unknown" /* OnlineState.Unknown */));
  13616. }
  13617. /**
  13618. * If not yet initialized, registers the WatchStream and its network state
  13619. * callback with `remoteStoreImpl`. Returns the existing stream if one is
  13620. * already available.
  13621. *
  13622. * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.
  13623. * This is not done on Web to allow it to be tree-shaken.
  13624. */ function tc(t) {
  13625. return t.pu || (
  13626. // Create stream (but note that it is not started yet).
  13627. t.pu = function(t, e, n) {
  13628. const s = $(t);
  13629. return s.su(), new Eu(e, s.connection, s.authCredentials, s.appCheckCredentials, s.yt, n);
  13630. }
  13631. /**
  13632. * @license
  13633. * Copyright 2018 Google LLC
  13634. *
  13635. * Licensed under the Apache License, Version 2.0 (the "License");
  13636. * you may not use this file except in compliance with the License.
  13637. * You may obtain a copy of the License at
  13638. *
  13639. * http://www.apache.org/licenses/LICENSE-2.0
  13640. *
  13641. * Unless required by applicable law or agreed to in writing, software
  13642. * distributed under the License is distributed on an "AS IS" BASIS,
  13643. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13644. * See the License for the specific language governing permissions and
  13645. * limitations under the License.
  13646. */ (t.datastore, t.asyncQueue, {
  13647. Yr: $u.bind(null, t),
  13648. Zr: Bu.bind(null, t),
  13649. Wo: Lu.bind(null, t)
  13650. }), t.wu.push((async e => {
  13651. e ? (t.pu.Mo(), Ou(t) ? ku(t) : t.gu.set("Unknown" /* OnlineState.Unknown */)) : (await t.pu.stop(),
  13652. Fu(t));
  13653. }))), t.pu;
  13654. }
  13655. /**
  13656. * If not yet initialized, registers the WriteStream and its network state
  13657. * callback with `remoteStoreImpl`. Returns the existing stream if one is
  13658. * already available.
  13659. *
  13660. * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.
  13661. * This is not done on Web to allow it to be tree-shaken.
  13662. */ function ec(t) {
  13663. return t.Iu || (
  13664. // Create stream (but note that it is not started yet).
  13665. t.Iu = function(t, e, n) {
  13666. const s = $(t);
  13667. return s.su(), new Au(e, s.connection, s.authCredentials, s.appCheckCredentials, s.yt, n);
  13668. }(t.datastore, t.asyncQueue, {
  13669. Yr: zu.bind(null, t),
  13670. Zr: Yu.bind(null, t),
  13671. tu: Hu.bind(null, t),
  13672. Zo: Ju.bind(null, t)
  13673. }), t.wu.push((async e => {
  13674. e ? (t.Iu.Mo(),
  13675. // This will start the write stream if necessary.
  13676. await Ku(t)) : (await t.Iu.stop(), t.fu.length > 0 && (C("RemoteStore", `Stopping write stream with ${t.fu.length} pending writes`),
  13677. t.fu = []));
  13678. }))), t.Iu;
  13679. }
  13680. /**
  13681. * @license
  13682. * Copyright 2017 Google LLC
  13683. *
  13684. * Licensed under the Apache License, Version 2.0 (the "License");
  13685. * you may not use this file except in compliance with the License.
  13686. * You may obtain a copy of the License at
  13687. *
  13688. * http://www.apache.org/licenses/LICENSE-2.0
  13689. *
  13690. * Unless required by applicable law or agreed to in writing, software
  13691. * distributed under the License is distributed on an "AS IS" BASIS,
  13692. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13693. * See the License for the specific language governing permissions and
  13694. * limitations under the License.
  13695. */
  13696. /**
  13697. * Represents an operation scheduled to be run in the future on an AsyncQueue.
  13698. *
  13699. * It is created via DelayedOperation.createAndSchedule().
  13700. *
  13701. * Supports cancellation (via cancel()) and early execution (via skipDelay()).
  13702. *
  13703. * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
  13704. * in newer versions of TypeScript defines `finally`, which is not available in
  13705. * IE.
  13706. */
  13707. class nc {
  13708. constructor(t, e, n, s, i) {
  13709. this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = s, this.removalCallback = i,
  13710. this.deferred = new q, this.then = this.deferred.promise.then.bind(this.deferred.promise),
  13711. // It's normal for the deferred promise to be canceled (due to cancellation)
  13712. // and so we attach a dummy catch callback to avoid
  13713. // 'UnhandledPromiseRejectionWarning' log spam.
  13714. this.deferred.promise.catch((t => {}));
  13715. }
  13716. /**
  13717. * Creates and returns a DelayedOperation that has been scheduled to be
  13718. * executed on the provided asyncQueue after the provided delayMs.
  13719. *
  13720. * @param asyncQueue - The queue to schedule the operation on.
  13721. * @param id - A Timer ID identifying the type of operation this is.
  13722. * @param delayMs - The delay (ms) before the operation should be scheduled.
  13723. * @param op - The operation to run.
  13724. * @param removalCallback - A callback to be called synchronously once the
  13725. * operation is executed or canceled, notifying the AsyncQueue to remove it
  13726. * from its delayedOperations list.
  13727. * PORTING NOTE: This exists to prevent making removeDelayedOperation() and
  13728. * the DelayedOperation class public.
  13729. */ static createAndSchedule(t, e, n, s, i) {
  13730. const r = Date.now() + n, o = new nc(t, e, r, s, i);
  13731. return o.start(n), o;
  13732. }
  13733. /**
  13734. * Starts the timer. This is called immediately after construction by
  13735. * createAndSchedule().
  13736. */ start(t) {
  13737. this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t);
  13738. }
  13739. /**
  13740. * Queues the operation to run immediately (if it hasn't already been run or
  13741. * canceled).
  13742. */ skipDelay() {
  13743. return this.handleDelayElapsed();
  13744. }
  13745. /**
  13746. * Cancels the operation if it hasn't already been executed or canceled. The
  13747. * promise will be rejected.
  13748. *
  13749. * As long as the operation has not yet been run, calling cancel() provides a
  13750. * guarantee that the operation will not be run.
  13751. */ cancel(t) {
  13752. null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new L(B.CANCELLED, "Operation cancelled" + (t ? ": " + t : ""))));
  13753. }
  13754. handleDelayElapsed() {
  13755. this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(),
  13756. this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve()));
  13757. }
  13758. clearTimeout() {
  13759. null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle),
  13760. this.timerHandle = null);
  13761. }
  13762. }
  13763. /**
  13764. * Returns a FirestoreError that can be surfaced to the user if the provided
  13765. * error is an IndexedDbTransactionError. Re-throws the error otherwise.
  13766. */ function sc(t, e) {
  13767. if (x("AsyncQueue", `${e}: ${t}`), Vt(t)) return new L(B.UNAVAILABLE, `${e}: ${t}`);
  13768. throw t;
  13769. }
  13770. /**
  13771. * @license
  13772. * Copyright 2017 Google LLC
  13773. *
  13774. * Licensed under the Apache License, Version 2.0 (the "License");
  13775. * you may not use this file except in compliance with the License.
  13776. * You may obtain a copy of the License at
  13777. *
  13778. * http://www.apache.org/licenses/LICENSE-2.0
  13779. *
  13780. * Unless required by applicable law or agreed to in writing, software
  13781. * distributed under the License is distributed on an "AS IS" BASIS,
  13782. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13783. * See the License for the specific language governing permissions and
  13784. * limitations under the License.
  13785. */
  13786. /**
  13787. * DocumentSet is an immutable (copy-on-write) collection that holds documents
  13788. * in order specified by the provided comparator. We always add a document key
  13789. * comparator on top of what is provided to guarantee document equality based on
  13790. * the key.
  13791. */ class ic {
  13792. /** The default ordering is by key if the comparator is omitted */
  13793. constructor(t) {
  13794. // We are adding document key comparator to the end as it's the only
  13795. // guaranteed unique property of a document.
  13796. this.comparator = t ? (e, n) => t(e, n) || ct.comparator(e.key, n.key) : (t, e) => ct.comparator(t.key, e.key),
  13797. this.keyedMap = ws(), this.sortedSet = new Ge(this.comparator);
  13798. }
  13799. /**
  13800. * Returns an empty copy of the existing DocumentSet, using the same
  13801. * comparator.
  13802. */ static emptySet(t) {
  13803. return new ic(t.comparator);
  13804. }
  13805. has(t) {
  13806. return null != this.keyedMap.get(t);
  13807. }
  13808. get(t) {
  13809. return this.keyedMap.get(t);
  13810. }
  13811. first() {
  13812. return this.sortedSet.minKey();
  13813. }
  13814. last() {
  13815. return this.sortedSet.maxKey();
  13816. }
  13817. isEmpty() {
  13818. return this.sortedSet.isEmpty();
  13819. }
  13820. /**
  13821. * Returns the index of the provided key in the document set, or -1 if the
  13822. * document key is not present in the set;
  13823. */ indexOf(t) {
  13824. const e = this.keyedMap.get(t);
  13825. return e ? this.sortedSet.indexOf(e) : -1;
  13826. }
  13827. get size() {
  13828. return this.sortedSet.size;
  13829. }
  13830. /** Iterates documents in order defined by "comparator" */ forEach(t) {
  13831. this.sortedSet.inorderTraversal(((e, n) => (t(e), !1)));
  13832. }
  13833. /** Inserts or updates a document with the same key */ add(t) {
  13834. // First remove the element if we have it.
  13835. const e = this.delete(t.key);
  13836. return e.copy(e.keyedMap.insert(t.key, t), e.sortedSet.insert(t, null));
  13837. }
  13838. /** Deletes a document with a given key */ delete(t) {
  13839. const e = this.get(t);
  13840. return e ? this.copy(this.keyedMap.remove(t), this.sortedSet.remove(e)) : this;
  13841. }
  13842. isEqual(t) {
  13843. if (!(t instanceof ic)) return !1;
  13844. if (this.size !== t.size) return !1;
  13845. const e = this.sortedSet.getIterator(), n = t.sortedSet.getIterator();
  13846. for (;e.hasNext(); ) {
  13847. const t = e.getNext().key, s = n.getNext().key;
  13848. if (!t.isEqual(s)) return !1;
  13849. }
  13850. return !0;
  13851. }
  13852. toString() {
  13853. const t = [];
  13854. return this.forEach((e => {
  13855. t.push(e.toString());
  13856. })), 0 === t.length ? "DocumentSet ()" : "DocumentSet (\n " + t.join(" \n") + "\n)";
  13857. }
  13858. copy(t, e) {
  13859. const n = new ic;
  13860. return n.comparator = this.comparator, n.keyedMap = t, n.sortedSet = e, n;
  13861. }
  13862. }
  13863. /**
  13864. * @license
  13865. * Copyright 2017 Google LLC
  13866. *
  13867. * Licensed under the Apache License, Version 2.0 (the "License");
  13868. * you may not use this file except in compliance with the License.
  13869. * You may obtain a copy of the License at
  13870. *
  13871. * http://www.apache.org/licenses/LICENSE-2.0
  13872. *
  13873. * Unless required by applicable law or agreed to in writing, software
  13874. * distributed under the License is distributed on an "AS IS" BASIS,
  13875. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13876. * See the License for the specific language governing permissions and
  13877. * limitations under the License.
  13878. */
  13879. /**
  13880. * DocumentChangeSet keeps track of a set of changes to docs in a query, merging
  13881. * duplicate events for the same doc.
  13882. */ class rc {
  13883. constructor() {
  13884. this.Tu = new Ge(ct.comparator);
  13885. }
  13886. track(t) {
  13887. const e = t.doc.key, n = this.Tu.get(e);
  13888. n ?
  13889. // Merge the new change with the existing change.
  13890. 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, {
  13891. type: n.type,
  13892. doc: t.doc
  13893. }) : 2 /* ChangeType.Modified */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Tu = this.Tu.insert(e, {
  13894. type: 2 /* ChangeType.Modified */ ,
  13895. doc: t.doc
  13896. }) : 2 /* ChangeType.Modified */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Tu = this.Tu.insert(e, {
  13897. type: 0 /* ChangeType.Added */ ,
  13898. doc: t.doc
  13899. }) : 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, {
  13900. type: 1 /* ChangeType.Removed */ ,
  13901. doc: n.doc
  13902. }) : 0 /* ChangeType.Added */ === t.type && 1 /* ChangeType.Removed */ === n.type ? this.Tu = this.Tu.insert(e, {
  13903. type: 2 /* ChangeType.Modified */ ,
  13904. doc: t.doc
  13905. }) :
  13906. // This includes these cases, which don't make sense:
  13907. // Added->Added
  13908. // Removed->Removed
  13909. // Modified->Added
  13910. // Removed->Modified
  13911. // Metadata->Added
  13912. // Removed->Metadata
  13913. O() : this.Tu = this.Tu.insert(e, t);
  13914. }
  13915. Eu() {
  13916. const t = [];
  13917. return this.Tu.inorderTraversal(((e, n) => {
  13918. t.push(n);
  13919. })), t;
  13920. }
  13921. }
  13922. class oc {
  13923. constructor(t, e, n, s, i, r, o, u, c) {
  13924. this.query = t, this.docs = e, this.oldDocs = n, this.docChanges = s, this.mutatedKeys = i,
  13925. this.fromCache = r, this.syncStateChanged = o, this.excludesMetadataChanges = u,
  13926. this.hasCachedResults = c;
  13927. }
  13928. /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(t, e, n, s, i) {
  13929. const r = [];
  13930. return e.forEach((t => {
  13931. r.push({
  13932. type: 0 /* ChangeType.Added */ ,
  13933. doc: t
  13934. });
  13935. })), new oc(t, e, ic.emptySet(e), r, n, s,
  13936. /* syncStateChanged= */ !0,
  13937. /* excludesMetadataChanges= */ !1, i);
  13938. }
  13939. get hasPendingWrites() {
  13940. return !this.mutatedKeys.isEmpty();
  13941. }
  13942. isEqual(t) {
  13943. if (!(this.fromCache === t.fromCache && this.hasCachedResults === t.hasCachedResults && this.syncStateChanged === t.syncStateChanged && this.mutatedKeys.isEqual(t.mutatedKeys) && In(this.query, t.query) && this.docs.isEqual(t.docs) && this.oldDocs.isEqual(t.oldDocs))) return !1;
  13944. const e = this.docChanges, n = t.docChanges;
  13945. if (e.length !== n.length) return !1;
  13946. for (let t = 0; t < e.length; t++) if (e[t].type !== n[t].type || !e[t].doc.isEqual(n[t].doc)) return !1;
  13947. return !0;
  13948. }
  13949. }
  13950. /**
  13951. * @license
  13952. * Copyright 2017 Google LLC
  13953. *
  13954. * Licensed under the Apache License, Version 2.0 (the "License");
  13955. * you may not use this file except in compliance with the License.
  13956. * You may obtain a copy of the License at
  13957. *
  13958. * http://www.apache.org/licenses/LICENSE-2.0
  13959. *
  13960. * Unless required by applicable law or agreed to in writing, software
  13961. * distributed under the License is distributed on an "AS IS" BASIS,
  13962. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13963. * See the License for the specific language governing permissions and
  13964. * limitations under the License.
  13965. */
  13966. /**
  13967. * Holds the listeners and the last received ViewSnapshot for a query being
  13968. * tracked by EventManager.
  13969. */ class uc {
  13970. constructor() {
  13971. this.Au = void 0, this.listeners = [];
  13972. }
  13973. }
  13974. class cc {
  13975. constructor() {
  13976. this.queries = new ls((t => Tn(t)), In), this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  13977. this.Ru = new Set;
  13978. }
  13979. }
  13980. async function ac(t, e) {
  13981. const n = $(t), s = e.query;
  13982. let i = !1, r = n.queries.get(s);
  13983. if (r || (i = !0, r = new uc), i) try {
  13984. r.Au = await n.onListen(s);
  13985. } catch (t) {
  13986. const n = sc(t, `Initialization of query '${En(e.query)}' failed`);
  13987. return void e.onError(n);
  13988. }
  13989. if (n.queries.set(s, r), r.listeners.push(e),
  13990. // Run global snapshot listeners if a consistent snapshot has been emitted.
  13991. e.bu(n.onlineState), r.Au) {
  13992. e.Pu(r.Au) && dc(n);
  13993. }
  13994. }
  13995. async function hc(t, e) {
  13996. const n = $(t), s = e.query;
  13997. let i = !1;
  13998. const r = n.queries.get(s);
  13999. if (r) {
  14000. const t = r.listeners.indexOf(e);
  14001. t >= 0 && (r.listeners.splice(t, 1), i = 0 === r.listeners.length);
  14002. }
  14003. if (i) return n.queries.delete(s), n.onUnlisten(s);
  14004. }
  14005. function lc(t, e) {
  14006. const n = $(t);
  14007. let s = !1;
  14008. for (const t of e) {
  14009. const e = t.query, i = n.queries.get(e);
  14010. if (i) {
  14011. for (const e of i.listeners) e.Pu(t) && (s = !0);
  14012. i.Au = t;
  14013. }
  14014. }
  14015. s && dc(n);
  14016. }
  14017. function fc(t, e, n) {
  14018. const s = $(t), i = s.queries.get(e);
  14019. if (i) for (const t of i.listeners) t.onError(n);
  14020. // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()
  14021. // after an error.
  14022. s.queries.delete(e);
  14023. }
  14024. // Call all global snapshot listeners that have been set.
  14025. function dc(t) {
  14026. t.Ru.forEach((t => {
  14027. t.next();
  14028. }));
  14029. }
  14030. /**
  14031. * QueryListener takes a series of internal view snapshots and determines
  14032. * when to raise the event.
  14033. *
  14034. * It uses an Observer to dispatch events.
  14035. */ class _c {
  14036. constructor(t, e, n) {
  14037. this.query = t, this.vu = e,
  14038. /**
  14039. * Initial snapshots (e.g. from cache) may not be propagated to the wrapped
  14040. * observer. This flag is set to true once we've actually raised an event.
  14041. */
  14042. this.Vu = !1, this.Su = null, this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  14043. this.options = n || {};
  14044. }
  14045. /**
  14046. * Applies the new ViewSnapshot to this listener, raising a user-facing event
  14047. * if applicable (depending on what changed, whether the user has opted into
  14048. * metadata-only changes, etc.). Returns true if a user-facing event was
  14049. * indeed raised.
  14050. */ Pu(t) {
  14051. if (!this.options.includeMetadataChanges) {
  14052. // Remove the metadata only changes.
  14053. const e = [];
  14054. for (const n of t.docChanges) 3 /* ChangeType.Metadata */ !== n.type && e.push(n);
  14055. t = new oc(t.query, t.docs, t.oldDocs, e, t.mutatedKeys, t.fromCache, t.syncStateChanged,
  14056. /* excludesMetadataChanges= */ !0, t.hasCachedResults);
  14057. }
  14058. let e = !1;
  14059. return this.Vu ? this.Du(t) && (this.vu.next(t), e = !0) : this.Cu(t, this.onlineState) && (this.xu(t),
  14060. e = !0), this.Su = t, e;
  14061. }
  14062. onError(t) {
  14063. this.vu.error(t);
  14064. }
  14065. /** Returns whether a snapshot was raised. */ bu(t) {
  14066. this.onlineState = t;
  14067. let e = !1;
  14068. return this.Su && !this.Vu && this.Cu(this.Su, t) && (this.xu(this.Su), e = !0),
  14069. e;
  14070. }
  14071. Cu(t, e) {
  14072. // Always raise the first event when we're synced
  14073. if (!t.fromCache) return !0;
  14074. // NOTE: We consider OnlineState.Unknown as online (it should become Offline
  14075. // or Online if we wait long enough).
  14076. const n = "Offline" /* OnlineState.Offline */ !== e;
  14077. // Don't raise the event if we're online, aren't synced yet (checked
  14078. // above) and are waiting for a sync.
  14079. return (!this.options.Nu || !n) && (!t.docs.isEmpty() || t.hasCachedResults || "Offline" /* OnlineState.Offline */ === e);
  14080. // Raise data from cache if we have any documents, have cached results before,
  14081. // or we are offline.
  14082. }
  14083. Du(t) {
  14084. // We don't need to handle includeDocumentMetadataChanges here because
  14085. // the Metadata only changes have already been stripped out if needed.
  14086. // At this point the only changes we will see are the ones we should
  14087. // propagate.
  14088. if (t.docChanges.length > 0) return !0;
  14089. const e = this.Su && this.Su.hasPendingWrites !== t.hasPendingWrites;
  14090. return !(!t.syncStateChanged && !e) && !0 === this.options.includeMetadataChanges;
  14091. // Generally we should have hit one of the cases above, but it's possible
  14092. // to get here if there were only metadata docChanges and they got
  14093. // stripped out.
  14094. }
  14095. xu(t) {
  14096. t = oc.fromInitialDocuments(t.query, t.docs, t.mutatedKeys, t.fromCache, t.hasCachedResults),
  14097. this.Vu = !0, this.vu.next(t);
  14098. }
  14099. }
  14100. /**
  14101. * @license
  14102. * Copyright 2020 Google LLC
  14103. *
  14104. * Licensed under the Apache License, Version 2.0 (the "License");
  14105. * you may not use this file except in compliance with the License.
  14106. * You may obtain a copy of the License at
  14107. *
  14108. * http://www.apache.org/licenses/LICENSE-2.0
  14109. *
  14110. * Unless required by applicable law or agreed to in writing, software
  14111. * distributed under the License is distributed on an "AS IS" BASIS,
  14112. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14113. * See the License for the specific language governing permissions and
  14114. * limitations under the License.
  14115. */
  14116. /**
  14117. * A complete element in the bundle stream, together with the byte length it
  14118. * occupies in the stream.
  14119. */ class wc {
  14120. constructor(t,
  14121. // How many bytes this element takes to store in the bundle.
  14122. e) {
  14123. this.ku = t, this.byteLength = e;
  14124. }
  14125. Ou() {
  14126. return "metadata" in this.ku;
  14127. }
  14128. }
  14129. /**
  14130. * @license
  14131. * Copyright 2020 Google LLC
  14132. *
  14133. * Licensed under the Apache License, Version 2.0 (the "License");
  14134. * you may not use this file except in compliance with the License.
  14135. * You may obtain a copy of the License at
  14136. *
  14137. * http://www.apache.org/licenses/LICENSE-2.0
  14138. *
  14139. * Unless required by applicable law or agreed to in writing, software
  14140. * distributed under the License is distributed on an "AS IS" BASIS,
  14141. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14142. * See the License for the specific language governing permissions and
  14143. * limitations under the License.
  14144. */
  14145. /**
  14146. * Helper to convert objects from bundles to model objects in the SDK.
  14147. */ class mc {
  14148. constructor(t) {
  14149. this.yt = t;
  14150. }
  14151. Ji(t) {
  14152. return Qs(this.yt, t);
  14153. }
  14154. /**
  14155. * Converts a BundleDocument to a MutableDocument.
  14156. */ Yi(t) {
  14157. return t.metadata.exists ? Ys(this.yt, t.document, !1) : Ze.newNoDocument(this.Ji(t.metadata.name), this.Xi(t.metadata.readTime));
  14158. }
  14159. Xi(t) {
  14160. return qs(t);
  14161. }
  14162. }
  14163. /**
  14164. * A class to process the elements from a bundle, load them into local
  14165. * storage and provide progress update while loading.
  14166. */ class gc {
  14167. constructor(t, e, n) {
  14168. this.Mu = t, this.localStore = e, this.yt = n,
  14169. /** Batched queries to be saved into storage */
  14170. this.queries = [],
  14171. /** Batched documents to be saved into storage */
  14172. this.documents = [],
  14173. /** The collection groups affected by this bundle. */
  14174. this.collectionGroups = new Set, this.progress = yc(t);
  14175. }
  14176. /**
  14177. * Adds an element from the bundle to the loader.
  14178. *
  14179. * Returns a new progress if adding the element leads to a new progress,
  14180. * otherwise returns null.
  14181. */ Fu(t) {
  14182. this.progress.bytesLoaded += t.byteLength;
  14183. let e = this.progress.documentsLoaded;
  14184. if (t.ku.namedQuery) this.queries.push(t.ku.namedQuery); else if (t.ku.documentMetadata) {
  14185. this.documents.push({
  14186. metadata: t.ku.documentMetadata
  14187. }), t.ku.documentMetadata.exists || ++e;
  14188. const n = rt.fromString(t.ku.documentMetadata.name);
  14189. this.collectionGroups.add(n.get(n.length - 2));
  14190. } else t.ku.document && (this.documents[this.documents.length - 1].document = t.ku.document,
  14191. ++e);
  14192. return e !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = e,
  14193. Object.assign({}, this.progress)) : null;
  14194. }
  14195. $u(t) {
  14196. const e = new Map, n = new mc(this.yt);
  14197. for (const s of t) if (s.metadata.queries) {
  14198. const t = n.Ji(s.metadata.name);
  14199. for (const n of s.metadata.queries) {
  14200. const s = (e.get(n) || Es()).add(t);
  14201. e.set(n, s);
  14202. }
  14203. }
  14204. return e;
  14205. }
  14206. /**
  14207. * Update the progress to 'Success' and return the updated progress.
  14208. */ async complete() {
  14209. const t = await tu(this.localStore, new mc(this.yt), this.documents, this.Mu.id), e = this.$u(this.documents);
  14210. for (const t of this.queries) await eu(this.localStore, t, e.get(t.name));
  14211. return this.progress.taskState = "Success", {
  14212. progress: this.progress,
  14213. Bu: this.collectionGroups,
  14214. Lu: t
  14215. };
  14216. }
  14217. }
  14218. /**
  14219. * Returns a `LoadBundleTaskProgress` representing the initial progress of
  14220. * loading a bundle.
  14221. */ function yc(t) {
  14222. return {
  14223. taskState: "Running",
  14224. documentsLoaded: 0,
  14225. bytesLoaded: 0,
  14226. totalDocuments: t.totalDocuments,
  14227. totalBytes: t.totalBytes
  14228. };
  14229. }
  14230. /**
  14231. * Returns a `LoadBundleTaskProgress` representing the progress that the loading
  14232. * has succeeded.
  14233. */
  14234. /**
  14235. * @license
  14236. * Copyright 2017 Google LLC
  14237. *
  14238. * Licensed under the Apache License, Version 2.0 (the "License");
  14239. * you may not use this file except in compliance with the License.
  14240. * You may obtain a copy of the License at
  14241. *
  14242. * http://www.apache.org/licenses/LICENSE-2.0
  14243. *
  14244. * Unless required by applicable law or agreed to in writing, software
  14245. * distributed under the License is distributed on an "AS IS" BASIS,
  14246. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14247. * See the License for the specific language governing permissions and
  14248. * limitations under the License.
  14249. */
  14250. class pc {
  14251. constructor(t) {
  14252. this.key = t;
  14253. }
  14254. }
  14255. class Ic {
  14256. constructor(t) {
  14257. this.key = t;
  14258. }
  14259. }
  14260. /**
  14261. * View is responsible for computing the final merged truth of what docs are in
  14262. * a query. It gets notified of local and remote changes to docs, and applies
  14263. * the query filters and limits to determine the most correct possible results.
  14264. */ class Tc {
  14265. constructor(t,
  14266. /** Documents included in the remote target */
  14267. e) {
  14268. this.query = t, this.qu = e, this.Uu = null, this.hasCachedResults = !1,
  14269. /**
  14270. * A flag whether the view is current with the backend. A view is considered
  14271. * current after it has seen the current flag from the backend and did not
  14272. * lose consistency within the watch stream (e.g. because of an existence
  14273. * filter mismatch).
  14274. */
  14275. this.current = !1,
  14276. /** Documents in the view but not in the remote target */
  14277. this.Ku = Es(),
  14278. /** Document Keys that have local changes */
  14279. this.mutatedKeys = Es(), this.Gu = bn(t), this.Qu = new ic(this.Gu);
  14280. }
  14281. /**
  14282. * The set of remote documents that the server has told us belongs to the target associated with
  14283. * this view.
  14284. */ get ju() {
  14285. return this.qu;
  14286. }
  14287. /**
  14288. * Iterates over a set of doc changes, applies the query limit, and computes
  14289. * what the new results should be, what the changes were, and whether we may
  14290. * need to go back to the local cache for more results. Does not make any
  14291. * changes to the view.
  14292. * @param docChanges - The doc changes to apply to this view.
  14293. * @param previousChanges - If this is being called with a refill, then start
  14294. * with this set of docs and changes instead of the current view.
  14295. * @returns a new set of docs, changes, and refill flag.
  14296. */ Wu(t, e) {
  14297. const n = e ? e.zu : new rc, s = e ? e.Qu : this.Qu;
  14298. let i = e ? e.mutatedKeys : this.mutatedKeys, r = s, o = !1;
  14299. // Track the last doc in a (full) limit. This is necessary, because some
  14300. // update (a delete, or an update moving a doc past the old limit) might
  14301. // mean there is some other document in the local cache that either should
  14302. // come (1) between the old last limit doc and the new last document, in the
  14303. // case of updates, or (2) after the new last document, in the case of
  14304. // deletes. So we keep this doc at the old limit to compare the updates to.
  14305. // Note that this should never get used in a refill (when previousChanges is
  14306. // set), because there will only be adds -- no deletes or updates.
  14307. const u = "F" /* LimitType.First */ === this.query.limitType && s.size === this.query.limit ? s.last() : null, c = "L" /* LimitType.Last */ === this.query.limitType && s.size === this.query.limit ? s.first() : null;
  14308. // Drop documents out to meet limit/limitToLast requirement.
  14309. if (t.inorderTraversal(((t, e) => {
  14310. const a = s.get(t), h = An(this.query, e) ? e : null, l = !!a && this.mutatedKeys.has(a.key), f = !!h && (h.hasLocalMutations ||
  14311. // We only consider committed mutations for documents that were
  14312. // mutated during the lifetime of the view.
  14313. this.mutatedKeys.has(h.key) && h.hasCommittedMutations);
  14314. let d = !1;
  14315. // Calculate change
  14316. if (a && h) {
  14317. a.data.isEqual(h.data) ? l !== f && (n.track({
  14318. type: 3 /* ChangeType.Metadata */ ,
  14319. doc: h
  14320. }), d = !0) : this.Hu(a, h) || (n.track({
  14321. type: 2 /* ChangeType.Modified */ ,
  14322. doc: h
  14323. }), d = !0, (u && this.Gu(h, u) > 0 || c && this.Gu(h, c) < 0) && (
  14324. // This doc moved from inside the limit to outside the limit.
  14325. // That means there may be some other doc in the local cache
  14326. // that should be included instead.
  14327. o = !0));
  14328. } else !a && h ? (n.track({
  14329. type: 0 /* ChangeType.Added */ ,
  14330. doc: h
  14331. }), d = !0) : a && !h && (n.track({
  14332. type: 1 /* ChangeType.Removed */ ,
  14333. doc: a
  14334. }), d = !0, (u || c) && (
  14335. // A doc was removed from a full limit query. We'll need to
  14336. // requery from the local cache to see if we know about some other
  14337. // doc that should be in the results.
  14338. o = !0));
  14339. d && (h ? (r = r.add(h), i = f ? i.add(t) : i.delete(t)) : (r = r.delete(t), i = i.delete(t)));
  14340. })), null !== this.query.limit) for (;r.size > this.query.limit; ) {
  14341. const t = "F" /* LimitType.First */ === this.query.limitType ? r.last() : r.first();
  14342. r = r.delete(t.key), i = i.delete(t.key), n.track({
  14343. type: 1 /* ChangeType.Removed */ ,
  14344. doc: t
  14345. });
  14346. }
  14347. return {
  14348. Qu: r,
  14349. zu: n,
  14350. $i: o,
  14351. mutatedKeys: i
  14352. };
  14353. }
  14354. Hu(t, e) {
  14355. // We suppress the initial change event for documents that were modified as
  14356. // part of a write acknowledgment (e.g. when the value of a server transform
  14357. // is applied) as Watch will send us the same document again.
  14358. // By suppressing the event, we only raise two user visible events (one with
  14359. // `hasPendingWrites` and the final state of the document) instead of three
  14360. // (one with `hasPendingWrites`, the modified document with
  14361. // `hasPendingWrites` and the final state of the document).
  14362. return t.hasLocalMutations && e.hasCommittedMutations && !e.hasLocalMutations;
  14363. }
  14364. /**
  14365. * Updates the view with the given ViewDocumentChanges and optionally updates
  14366. * limbo docs and sync state from the provided target change.
  14367. * @param docChanges - The set of changes to make to the view's docs.
  14368. * @param updateLimboDocuments - Whether to update limbo documents based on
  14369. * this change.
  14370. * @param targetChange - A target change to apply for computing limbo docs and
  14371. * sync state.
  14372. * @returns A new ViewChange with the given docs, changes, and sync state.
  14373. */
  14374. // PORTING NOTE: The iOS/Android clients always compute limbo document changes.
  14375. applyChanges(t, e, n) {
  14376. const s = this.Qu;
  14377. this.Qu = t.Qu, this.mutatedKeys = t.mutatedKeys;
  14378. // Sort changes based on type and query comparator
  14379. const i = t.zu.Eu();
  14380. i.sort(((t, e) => function(t, e) {
  14381. const n = t => {
  14382. switch (t) {
  14383. case 0 /* ChangeType.Added */ :
  14384. return 1;
  14385. case 2 /* ChangeType.Modified */ :
  14386. case 3 /* ChangeType.Metadata */ :
  14387. // A metadata change is converted to a modified change at the public
  14388. // api layer. Since we sort by document key and then change type,
  14389. // metadata and modified changes must be sorted equivalently.
  14390. return 2;
  14391. case 1 /* ChangeType.Removed */ :
  14392. return 0;
  14393. default:
  14394. return O();
  14395. }
  14396. };
  14397. return n(t) - n(e);
  14398. }
  14399. /**
  14400. * @license
  14401. * Copyright 2020 Google LLC
  14402. *
  14403. * Licensed under the Apache License, Version 2.0 (the "License");
  14404. * you may not use this file except in compliance with the License.
  14405. * You may obtain a copy of the License at
  14406. *
  14407. * http://www.apache.org/licenses/LICENSE-2.0
  14408. *
  14409. * Unless required by applicable law or agreed to in writing, software
  14410. * distributed under the License is distributed on an "AS IS" BASIS,
  14411. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14412. * See the License for the specific language governing permissions and
  14413. * limitations under the License.
  14414. */ (t.type, e.type) || this.Gu(t.doc, e.doc))), this.Ju(n);
  14415. const r = e ? this.Yu() : [], o = 0 === this.Ku.size && this.current ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , u = o !== this.Uu;
  14416. if (this.Uu = o, 0 !== i.length || u) {
  14417. return {
  14418. snapshot: new oc(this.query, t.Qu, s, i, t.mutatedKeys, 0 /* SyncState.Local */ === o, u,
  14419. /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0),
  14420. Xu: r
  14421. };
  14422. }
  14423. // no changes
  14424. return {
  14425. Xu: r
  14426. };
  14427. }
  14428. /**
  14429. * Applies an OnlineState change to the view, potentially generating a
  14430. * ViewChange if the view's syncState changes as a result.
  14431. */ bu(t) {
  14432. return this.current && "Offline" /* OnlineState.Offline */ === t ? (
  14433. // If we're offline, set `current` to false and then call applyChanges()
  14434. // to refresh our syncState and generate a ViewChange as appropriate. We
  14435. // are guaranteed to get a new TargetChange that sets `current` back to
  14436. // true once the client is back online.
  14437. this.current = !1, this.applyChanges({
  14438. Qu: this.Qu,
  14439. zu: new rc,
  14440. mutatedKeys: this.mutatedKeys,
  14441. $i: !1
  14442. },
  14443. /* updateLimboDocuments= */ !1)) : {
  14444. Xu: []
  14445. };
  14446. }
  14447. /**
  14448. * Returns whether the doc for the given key should be in limbo.
  14449. */ Zu(t) {
  14450. // If the remote end says it's part of this query, it's not in limbo.
  14451. return !this.qu.has(t) && (
  14452. // The local store doesn't think it's a result, so it shouldn't be in limbo.
  14453. !!this.Qu.has(t) && !this.Qu.get(t).hasLocalMutations);
  14454. }
  14455. /**
  14456. * Updates syncedDocuments, current, and limbo docs based on the given change.
  14457. * Returns the list of changes to which docs are in limbo.
  14458. */ Ju(t) {
  14459. t && (t.addedDocuments.forEach((t => this.qu = this.qu.add(t))), t.modifiedDocuments.forEach((t => {})),
  14460. t.removedDocuments.forEach((t => this.qu = this.qu.delete(t))), this.current = t.current);
  14461. }
  14462. Yu() {
  14463. // We can only determine limbo documents when we're in-sync with the server.
  14464. if (!this.current) return [];
  14465. // TODO(klimt): Do this incrementally so that it's not quadratic when
  14466. // updating many documents.
  14467. const t = this.Ku;
  14468. this.Ku = Es(), this.Qu.forEach((t => {
  14469. this.Zu(t.key) && (this.Ku = this.Ku.add(t.key));
  14470. }));
  14471. // Diff the new limbo docs with the old limbo docs.
  14472. const e = [];
  14473. return t.forEach((t => {
  14474. this.Ku.has(t) || e.push(new Ic(t));
  14475. })), this.Ku.forEach((n => {
  14476. t.has(n) || e.push(new pc(n));
  14477. })), e;
  14478. }
  14479. /**
  14480. * Update the in-memory state of the current view with the state read from
  14481. * persistence.
  14482. *
  14483. * We update the query view whenever a client's primary status changes:
  14484. * - When a client transitions from primary to secondary, it can miss
  14485. * LocalStorage updates and its query views may temporarily not be
  14486. * synchronized with the state on disk.
  14487. * - For secondary to primary transitions, the client needs to update the list
  14488. * of `syncedDocuments` since secondary clients update their query views
  14489. * based purely on synthesized RemoteEvents.
  14490. *
  14491. * @param queryResult.documents - The documents that match the query according
  14492. * to the LocalStore.
  14493. * @param queryResult.remoteKeys - The keys of the documents that match the
  14494. * query according to the backend.
  14495. *
  14496. * @returns The ViewChange that resulted from this synchronization.
  14497. */
  14498. // PORTING NOTE: Multi-tab only.
  14499. tc(t) {
  14500. this.qu = t.Hi, this.Ku = Es();
  14501. const e = this.Wu(t.documents);
  14502. return this.applyChanges(e, /*updateLimboDocuments=*/ !0);
  14503. }
  14504. /**
  14505. * Returns a view snapshot as if this query was just listened to. Contains
  14506. * a document add for every existing document and the `fromCache` and
  14507. * `hasPendingWrites` status of the already established view.
  14508. */
  14509. // PORTING NOTE: Multi-tab only.
  14510. ec() {
  14511. return oc.fromInitialDocuments(this.query, this.Qu, this.mutatedKeys, 0 /* SyncState.Local */ === this.Uu, this.hasCachedResults);
  14512. }
  14513. }
  14514. /**
  14515. * QueryView contains all of the data that SyncEngine needs to keep track of for
  14516. * a particular query.
  14517. */
  14518. class Ec {
  14519. constructor(
  14520. /**
  14521. * The query itself.
  14522. */
  14523. t,
  14524. /**
  14525. * The target number created by the client that is used in the watch
  14526. * stream to identify this query.
  14527. */
  14528. e,
  14529. /**
  14530. * The view is responsible for computing the final merged truth of what
  14531. * docs are in the query. It gets notified of local and remote changes,
  14532. * and applies the query filters and limits to determine the most correct
  14533. * possible results.
  14534. */
  14535. n) {
  14536. this.query = t, this.targetId = e, this.view = n;
  14537. }
  14538. }
  14539. /** Tracks a limbo resolution. */ class Ac {
  14540. constructor(t) {
  14541. this.key = t,
  14542. /**
  14543. * Set to true once we've received a document. This is used in
  14544. * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to
  14545. * decide whether it needs to manufacture a delete event for the target once
  14546. * the target is CURRENT.
  14547. */
  14548. this.nc = !1;
  14549. }
  14550. }
  14551. /**
  14552. * An implementation of `SyncEngine` coordinating with other parts of SDK.
  14553. *
  14554. * The parts of SyncEngine that act as a callback to RemoteStore need to be
  14555. * registered individually. This is done in `syncEngineWrite()` and
  14556. * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods
  14557. * serve as entry points to RemoteStore's functionality.
  14558. *
  14559. * Note: some field defined in this class might have public access level, but
  14560. * the class is not exported so they are only accessible from this module.
  14561. * This is useful to implement optional features (like bundles) in free
  14562. * functions, such that they are tree-shakeable.
  14563. */ class Rc {
  14564. constructor(t, e, n,
  14565. // PORTING NOTE: Manages state synchronization in multi-tab environments.
  14566. s, i, r) {
  14567. this.localStore = t, this.remoteStore = e, this.eventManager = n, this.sharedClientState = s,
  14568. this.currentUser = i, this.maxConcurrentLimboResolutions = r, this.sc = {}, this.ic = new ls((t => Tn(t)), In),
  14569. this.rc = new Map,
  14570. /**
  14571. * The keys of documents that are in limbo for which we haven't yet started a
  14572. * limbo resolution query. The strings in this set are the result of calling
  14573. * `key.path.canonicalString()` where `key` is a `DocumentKey` object.
  14574. *
  14575. * The `Set` type was chosen because it provides efficient lookup and removal
  14576. * of arbitrary elements and it also maintains insertion order, providing the
  14577. * desired queue-like FIFO semantics.
  14578. */
  14579. this.oc = new Set,
  14580. /**
  14581. * Keeps track of the target ID for each document that is in limbo with an
  14582. * active target.
  14583. */
  14584. this.uc = new Ge(ct.comparator),
  14585. /**
  14586. * Keeps track of the information about an active limbo resolution for each
  14587. * active target ID that was started for the purpose of limbo resolution.
  14588. */
  14589. this.cc = new Map, this.ac = new Eo,
  14590. /** Stores user completion handlers, indexed by User and BatchId. */
  14591. this.hc = {},
  14592. /** Stores user callbacks waiting for all pending writes to be acknowledged. */
  14593. this.lc = new Map, this.fc = Yr.vn(), this.onlineState = "Unknown" /* OnlineState.Unknown */ ,
  14594. // The primary state is set to `true` or `false` immediately after Firestore
  14595. // startup. In the interim, a client should only be considered primary if
  14596. // `isPrimary` is true.
  14597. this.dc = void 0;
  14598. }
  14599. get isPrimaryClient() {
  14600. return !0 === this.dc;
  14601. }
  14602. }
  14603. /**
  14604. * Initiates the new listen, resolves promise when listen enqueued to the
  14605. * server. All the subsequent view snapshots or errors are sent to the
  14606. * subscribed handlers. Returns the initial snapshot.
  14607. */
  14608. async function bc(t, e) {
  14609. const n = ta(t);
  14610. let s, i;
  14611. const r = n.ic.get(e);
  14612. if (r)
  14613. // PORTING NOTE: With Multi-Tab Web, it is possible that a query view
  14614. // already exists when EventManager calls us for the first time. This
  14615. // happens when the primary tab is already listening to this query on
  14616. // behalf of another tab and the user of the primary also starts listening
  14617. // to the query. EventManager will not have an assigned target ID in this
  14618. // case and calls `listen` to obtain this ID.
  14619. s = r.targetId, n.sharedClientState.addLocalQueryTarget(s), i = r.view.ec(); else {
  14620. const t = await zo(n.localStore, gn(e));
  14621. n.isPrimaryClient && Du(n.remoteStore, t);
  14622. const r = n.sharedClientState.addLocalQueryTarget(t.targetId);
  14623. s = t.targetId, i = await Pc(n, e, s, "current" === r, t.resumeToken);
  14624. }
  14625. return i;
  14626. }
  14627. /**
  14628. * Registers a view for a previously unknown query and computes its initial
  14629. * snapshot.
  14630. */ async function Pc(t, e, n, s, i) {
  14631. // PORTING NOTE: On Web only, we inject the code that registers new Limbo
  14632. // targets based on view changes. This allows us to only depend on Limbo
  14633. // changes when user code includes queries.
  14634. t._c = (e, n, s) => async function(t, e, n, s) {
  14635. let i = e.view.Wu(n);
  14636. i.$i && (
  14637. // The query has a limit and some docs were removed, so we need
  14638. // to re-run the query against the local store to make sure we
  14639. // didn't lose any good docs that had been past the limit.
  14640. i = await Jo(t.localStore, e.query,
  14641. /* usePreviousResults= */ !1).then((({documents: t}) => e.view.Wu(t, i))));
  14642. const r = s && s.targetChanges.get(e.targetId), o = e.view.applyChanges(i,
  14643. /* updateLimboDocuments= */ t.isPrimaryClient, r);
  14644. return Bc(t, e.targetId, o.Xu), o.snapshot;
  14645. }(t, e, n, s);
  14646. const r = await Jo(t.localStore, e,
  14647. /* usePreviousResults= */ !0), o = new Tc(e, r.Hi), u = o.Wu(r.documents), c = Ps.createSynthesizedTargetChangeForCurrentChange(n, s && "Offline" /* OnlineState.Offline */ !== t.onlineState, i), a = o.applyChanges(u,
  14648. /* updateLimboDocuments= */ t.isPrimaryClient, c);
  14649. Bc(t, n, a.Xu);
  14650. const h = new Ec(e, n, o);
  14651. return t.ic.set(e, h), t.rc.has(n) ? t.rc.get(n).push(e) : t.rc.set(n, [ e ]), a.snapshot;
  14652. }
  14653. /** Stops listening to the query. */ async function vc(t, e) {
  14654. const n = $(t), s = n.ic.get(e), i = n.rc.get(s.targetId);
  14655. if (i.length > 1) return n.rc.set(s.targetId, i.filter((t => !In(t, e)))), void n.ic.delete(e);
  14656. // No other queries are mapped to the target, clean up the query and the target.
  14657. if (n.isPrimaryClient) {
  14658. // We need to remove the local query target first to allow us to verify
  14659. // whether any other client is still interested in this target.
  14660. n.sharedClientState.removeLocalQueryTarget(s.targetId);
  14661. n.sharedClientState.isActiveQueryTarget(s.targetId) || await Ho(n.localStore, s.targetId,
  14662. /*keepPersistedTargetData=*/ !1).then((() => {
  14663. n.sharedClientState.clearQueryState(s.targetId), Cu(n.remoteStore, s.targetId),
  14664. Fc(n, s.targetId);
  14665. })).catch(Et);
  14666. } else Fc(n, s.targetId), await Ho(n.localStore, s.targetId,
  14667. /*keepPersistedTargetData=*/ !0);
  14668. }
  14669. /**
  14670. * Initiates the write of local mutation batch which involves adding the
  14671. * writes to the mutation queue, notifying the remote store about new
  14672. * mutations and raising events for any changes this write caused.
  14673. *
  14674. * The promise returned by this call is resolved when the above steps
  14675. * have completed, *not* when the write was acked by the backend. The
  14676. * userCallback is resolved once the write was acked/rejected by the
  14677. * backend (or failed locally for any other reason).
  14678. */ async function Vc(t, e, n) {
  14679. const s = ea(t);
  14680. try {
  14681. const t = await function(t, e) {
  14682. const n = $(t), s = nt.now(), i = e.reduce(((t, e) => t.add(e.key)), Es());
  14683. let r, o;
  14684. return n.persistence.runTransaction("Locally write mutations", "readwrite", (t => {
  14685. // Figure out which keys do not have a remote version in the cache, this
  14686. // is needed to create the right overlay mutation: if no remote version
  14687. // presents, we do not need to create overlays as patch mutations.
  14688. // TODO(Overlay): Is there a better way to determine this? Using the
  14689. // document version does not work because local mutations set them back
  14690. // to 0.
  14691. let u = ds(), c = Es();
  14692. return n.Gi.getEntries(t, i).next((t => {
  14693. u = t, u.forEach(((t, e) => {
  14694. e.isValidDocument() || (c = c.add(t));
  14695. }));
  14696. })).next((() => n.localDocuments.getOverlayedDocuments(t, u))).next((i => {
  14697. r = i;
  14698. // For non-idempotent mutations (such as `FieldValue.increment()`),
  14699. // we record the base state in a separate patch mutation. This is
  14700. // later used to guarantee consistent values and prevents flicker
  14701. // even if the backend sends us an update that already includes our
  14702. // transform.
  14703. const o = [];
  14704. for (const t of e) {
  14705. const e = Yn(t, r.get(t.key).overlayedDocument);
  14706. null != e &&
  14707. // NOTE: The base state should only be applied if there's some
  14708. // existing document to override, so use a Precondition of
  14709. // exists=true
  14710. o.push(new ts(t.key, e, Xe(e.value.mapValue), Qn.exists(!0)));
  14711. }
  14712. return n.mutationQueue.addMutationBatch(t, s, o, e);
  14713. })).next((e => {
  14714. o = e;
  14715. const s = e.applyToLocalDocumentSet(r, c);
  14716. return n.documentOverlayCache.saveOverlays(t, e.batchId, s);
  14717. }));
  14718. })).then((() => ({
  14719. batchId: o.batchId,
  14720. changes: ms(r)
  14721. })));
  14722. }(s.localStore, e);
  14723. s.sharedClientState.addPendingMutation(t.batchId), function(t, e, n) {
  14724. let s = t.hc[t.currentUser.toKey()];
  14725. s || (s = new Ge(Z));
  14726. s = s.insert(e, n), t.hc[t.currentUser.toKey()] = s;
  14727. }
  14728. /**
  14729. * Resolves or rejects the user callback for the given batch and then discards
  14730. * it.
  14731. */ (s, t.batchId, n), await Uc(s, t.changes), await Ku(s.remoteStore);
  14732. } catch (t) {
  14733. // If we can't persist the mutation, we reject the user callback and
  14734. // don't send the mutation. The user can then retry the write.
  14735. const e = sc(t, "Failed to persist write");
  14736. n.reject(e);
  14737. }
  14738. }
  14739. /**
  14740. * Applies one remote event to the sync engine, notifying any views of the
  14741. * changes, and releasing any pending mutation batches that would become
  14742. * visible because of the snapshot version the remote event contains.
  14743. */ async function Sc(t, e) {
  14744. const n = $(t);
  14745. try {
  14746. const t = await Qo(n.localStore, e);
  14747. // Update `receivedDocument` as appropriate for any limbo targets.
  14748. e.targetChanges.forEach(((t, e) => {
  14749. const s = n.cc.get(e);
  14750. s && (
  14751. // Since this is a limbo resolution lookup, it's for a single document
  14752. // and it could be added, modified, or removed, but not a combination.
  14753. M(t.addedDocuments.size + t.modifiedDocuments.size + t.removedDocuments.size <= 1),
  14754. t.addedDocuments.size > 0 ? s.nc = !0 : t.modifiedDocuments.size > 0 ? M(s.nc) : t.removedDocuments.size > 0 && (M(s.nc),
  14755. s.nc = !1));
  14756. })), await Uc(n, t, e);
  14757. } catch (t) {
  14758. await Et(t);
  14759. }
  14760. }
  14761. /**
  14762. * Applies an OnlineState change to the sync engine and notifies any views of
  14763. * the change.
  14764. */ function Dc(t, e, n) {
  14765. const s = $(t);
  14766. // If we are the secondary client, we explicitly ignore the remote store's
  14767. // online state (the local client may go offline, even though the primary
  14768. // tab remains online) and only apply the primary tab's online state from
  14769. // SharedClientState.
  14770. if (s.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !s.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) {
  14771. const t = [];
  14772. s.ic.forEach(((n, s) => {
  14773. const i = s.view.bu(e);
  14774. i.snapshot && t.push(i.snapshot);
  14775. })), function(t, e) {
  14776. const n = $(t);
  14777. n.onlineState = e;
  14778. let s = !1;
  14779. n.queries.forEach(((t, n) => {
  14780. for (const t of n.listeners)
  14781. // Run global snapshot listeners if a consistent snapshot has been emitted.
  14782. t.bu(e) && (s = !0);
  14783. })), s && dc(n);
  14784. }(s.eventManager, e), t.length && s.sc.Wo(t), s.onlineState = e, s.isPrimaryClient && s.sharedClientState.setOnlineState(e);
  14785. }
  14786. }
  14787. /**
  14788. * Rejects the listen for the given targetID. This can be triggered by the
  14789. * backend for any active target.
  14790. *
  14791. * @param syncEngine - The sync engine implementation.
  14792. * @param targetId - The targetID corresponds to one previously initiated by the
  14793. * user as part of TargetData passed to listen() on RemoteStore.
  14794. * @param err - A description of the condition that has forced the rejection.
  14795. * Nearly always this will be an indication that the user is no longer
  14796. * authorized to see the data matching the target.
  14797. */ async function Cc(t, e, n) {
  14798. const s = $(t);
  14799. // PORTING NOTE: Multi-tab only.
  14800. s.sharedClientState.updateQueryState(e, "rejected", n);
  14801. const i = s.cc.get(e), r = i && i.key;
  14802. if (r) {
  14803. // TODO(klimt): We really only should do the following on permission
  14804. // denied errors, but we don't have the cause code here.
  14805. // It's a limbo doc. Create a synthetic event saying it was deleted.
  14806. // This is kind of a hack. Ideally, we would have a method in the local
  14807. // store to purge a document. However, it would be tricky to keep all of
  14808. // the local store's invariants with another method.
  14809. let t = new Ge(ct.comparator);
  14810. // TODO(b/217189216): This limbo document should ideally have a read time,
  14811. // so that it is picked up by any read-time based scans. The backend,
  14812. // however, does not send a read time for target removals.
  14813. t = t.insert(r, Ze.newNoDocument(r, st.min()));
  14814. const n = Es().add(r), i = new bs(st.min(),
  14815. /* targetChanges= */ new Map,
  14816. /* targetMismatches= */ new We(Z), t, n);
  14817. await Sc(s, i),
  14818. // Since this query failed, we won't want to manually unlisten to it.
  14819. // We only remove it from bookkeeping after we successfully applied the
  14820. // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to
  14821. // this query when the RemoteStore restarts the Watch stream, which should
  14822. // re-trigger the target failure.
  14823. s.uc = s.uc.remove(r), s.cc.delete(e), qc(s);
  14824. } else await Ho(s.localStore, e,
  14825. /* keepPersistedTargetData */ !1).then((() => Fc(s, e, n))).catch(Et);
  14826. }
  14827. async function xc(t, e) {
  14828. const n = $(t), s = e.batch.batchId;
  14829. try {
  14830. const t = await Ko(n.localStore, e);
  14831. // The local store may or may not be able to apply the write result and
  14832. // raise events immediately (depending on whether the watcher is caught
  14833. // up), so we raise user callbacks first so that they consistently happen
  14834. // before listen events.
  14835. Mc(n, s, /*error=*/ null), Oc(n, s), n.sharedClientState.updateMutationState(s, "acknowledged"),
  14836. await Uc(n, t);
  14837. } catch (t) {
  14838. await Et(t);
  14839. }
  14840. }
  14841. async function Nc(t, e, n) {
  14842. const s = $(t);
  14843. try {
  14844. const t = await function(t, e) {
  14845. const n = $(t);
  14846. return n.persistence.runTransaction("Reject batch", "readwrite-primary", (t => {
  14847. let s;
  14848. return n.mutationQueue.lookupMutationBatch(t, e).next((e => (M(null !== e), s = e.keys(),
  14849. n.mutationQueue.removeMutationBatch(t, e)))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, s))).next((() => n.localDocuments.getDocuments(t, s)));
  14850. }));
  14851. }
  14852. /**
  14853. * Returns the largest (latest) batch id in mutation queue that is pending
  14854. * server response.
  14855. *
  14856. * Returns `BATCHID_UNKNOWN` if the queue is empty.
  14857. */ (s.localStore, e);
  14858. // The local store may or may not be able to apply the write result and
  14859. // raise events immediately (depending on whether the watcher is caught up),
  14860. // so we raise user callbacks first so that they consistently happen before
  14861. // listen events.
  14862. Mc(s, e, n), Oc(s, e), s.sharedClientState.updateMutationState(e, "rejected", n),
  14863. await Uc(s, t);
  14864. } catch (n) {
  14865. await Et(n);
  14866. }
  14867. }
  14868. /**
  14869. * Registers a user callback that resolves when all pending mutations at the moment of calling
  14870. * are acknowledged .
  14871. */ async function kc(t, e) {
  14872. const n = $(t);
  14873. Mu(n.remoteStore) || C("SyncEngine", "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");
  14874. try {
  14875. const t = await function(t) {
  14876. const e = $(t);
  14877. return e.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", (t => e.mutationQueue.getHighestUnacknowledgedBatchId(t)));
  14878. }(n.localStore);
  14879. if (-1 === t)
  14880. // Trigger the callback right away if there is no pending writes at the moment.
  14881. return void e.resolve();
  14882. const s = n.lc.get(t) || [];
  14883. s.push(e), n.lc.set(t, s);
  14884. } catch (t) {
  14885. const n = sc(t, "Initialization of waitForPendingWrites() operation failed");
  14886. e.reject(n);
  14887. }
  14888. }
  14889. /**
  14890. * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,
  14891. * if there are any.
  14892. */ function Oc(t, e) {
  14893. (t.lc.get(e) || []).forEach((t => {
  14894. t.resolve();
  14895. })), t.lc.delete(e);
  14896. }
  14897. /** Reject all outstanding callbacks waiting for pending writes to complete. */ function Mc(t, e, n) {
  14898. const s = $(t);
  14899. let i = s.hc[s.currentUser.toKey()];
  14900. // NOTE: Mutations restored from persistence won't have callbacks, so it's
  14901. // okay for there to be no callback for this ID.
  14902. if (i) {
  14903. const t = i.get(e);
  14904. t && (n ? t.reject(n) : t.resolve(), i = i.remove(e)), s.hc[s.currentUser.toKey()] = i;
  14905. }
  14906. }
  14907. function Fc(t, e, n = null) {
  14908. t.sharedClientState.removeLocalQueryTarget(e);
  14909. for (const s of t.rc.get(e)) t.ic.delete(s), n && t.sc.wc(s, n);
  14910. if (t.rc.delete(e), t.isPrimaryClient) {
  14911. t.ac.ls(e).forEach((e => {
  14912. t.ac.containsKey(e) ||
  14913. // We removed the last reference for this key
  14914. $c(t, e);
  14915. }));
  14916. }
  14917. }
  14918. function $c(t, e) {
  14919. t.oc.delete(e.path.canonicalString());
  14920. // It's possible that the target already got removed because the query failed. In that case,
  14921. // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.
  14922. const n = t.uc.get(e);
  14923. null !== n && (Cu(t.remoteStore, n), t.uc = t.uc.remove(e), t.cc.delete(n), qc(t));
  14924. }
  14925. function Bc(t, e, n) {
  14926. for (const s of n) if (s instanceof pc) t.ac.addReference(s.key, e), Lc(t, s); else if (s instanceof Ic) {
  14927. C("SyncEngine", "Document no longer in limbo: " + s.key), t.ac.removeReference(s.key, e);
  14928. t.ac.containsKey(s.key) ||
  14929. // We removed the last reference for this key
  14930. $c(t, s.key);
  14931. } else O();
  14932. }
  14933. function Lc(t, e) {
  14934. const n = e.key, s = n.path.canonicalString();
  14935. t.uc.get(n) || t.oc.has(s) || (C("SyncEngine", "New document in limbo: " + n), t.oc.add(s),
  14936. qc(t));
  14937. }
  14938. /**
  14939. * Starts listens for documents in limbo that are enqueued for resolution,
  14940. * subject to a maximum number of concurrent resolutions.
  14941. *
  14942. * Without bounding the number of concurrent resolutions, the server can fail
  14943. * with "resource exhausted" errors which can lead to pathological client
  14944. * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.
  14945. */ function qc(t) {
  14946. for (;t.oc.size > 0 && t.uc.size < t.maxConcurrentLimboResolutions; ) {
  14947. const e = t.oc.values().next().value;
  14948. t.oc.delete(e);
  14949. const n = new ct(rt.fromString(e)), s = t.fc.next();
  14950. t.cc.set(s, new Ac(n)), t.uc = t.uc.insert(n, s), Du(t.remoteStore, new zi(gn(ln(n.path)), s, 2 /* TargetPurpose.LimboResolution */ , Ot.at));
  14951. }
  14952. }
  14953. async function Uc(t, e, n) {
  14954. const s = $(t), i = [], r = [], o = [];
  14955. s.ic.isEmpty() || (s.ic.forEach(((t, u) => {
  14956. o.push(s._c(u, e, n).then((t => {
  14957. // Update views if there are actual changes.
  14958. if (
  14959. // If there are changes, or we are handling a global snapshot, notify
  14960. // secondary clients to update query state.
  14961. (t || n) && s.isPrimaryClient && s.sharedClientState.updateQueryState(u.targetId, (null == t ? void 0 : t.fromCache) ? "not-current" : "current"),
  14962. t) {
  14963. i.push(t);
  14964. const e = $o.Ci(u.targetId, t);
  14965. r.push(e);
  14966. }
  14967. })));
  14968. })), await Promise.all(o), s.sc.Wo(i), await async function(t, e) {
  14969. const n = $(t);
  14970. try {
  14971. await n.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (t => At.forEach(e, (e => At.forEach(e.Si, (s => n.persistence.referenceDelegate.addReference(t, e.targetId, s))).next((() => At.forEach(e.Di, (s => n.persistence.referenceDelegate.removeReference(t, e.targetId, s)))))))));
  14972. } catch (t) {
  14973. if (!Vt(t)) throw t;
  14974. // If `notifyLocalViewChanges` fails, we did not advance the sequence
  14975. // number for the documents that were included in this transaction.
  14976. // This might trigger them to be deleted earlier than they otherwise
  14977. // would have, but it should not invalidate the integrity of the data.
  14978. C("LocalStore", "Failed to update sequence numbers: " + t);
  14979. }
  14980. for (const t of e) {
  14981. const e = t.targetId;
  14982. if (!t.fromCache) {
  14983. const t = n.qi.get(e), s = t.snapshotVersion, i = t.withLastLimboFreeSnapshotVersion(s);
  14984. // Advance the last limbo free snapshot version
  14985. n.qi = n.qi.insert(e, i);
  14986. }
  14987. }
  14988. }(s.localStore, r));
  14989. }
  14990. async function Kc(t, e) {
  14991. const n = $(t);
  14992. if (!n.currentUser.isEqual(e)) {
  14993. C("SyncEngine", "User change. New user:", e.toKey());
  14994. const t = await Uo(n.localStore, e);
  14995. n.currentUser = e,
  14996. // Fails tasks waiting for pending writes requested by previous user.
  14997. function(t, e) {
  14998. t.lc.forEach((t => {
  14999. t.forEach((t => {
  15000. t.reject(new L(B.CANCELLED, e));
  15001. }));
  15002. })), t.lc.clear();
  15003. }(n, "'waitForPendingWrites' promise is rejected due to a user change."),
  15004. // TODO(b/114226417): Consider calling this only in the primary tab.
  15005. n.sharedClientState.handleUserChange(e, t.removedBatchIds, t.addedBatchIds), await Uc(n, t.ji);
  15006. }
  15007. }
  15008. function Gc(t, e) {
  15009. const n = $(t), s = n.cc.get(e);
  15010. if (s && s.nc) return Es().add(s.key);
  15011. {
  15012. let t = Es();
  15013. const s = n.rc.get(e);
  15014. if (!s) return t;
  15015. for (const e of s) {
  15016. const s = n.ic.get(e);
  15017. t = t.unionWith(s.view.ju);
  15018. }
  15019. return t;
  15020. }
  15021. }
  15022. /**
  15023. * Reconcile the list of synced documents in an existing view with those
  15024. * from persistence.
  15025. */ async function Qc(t, e) {
  15026. const n = $(t), s = await Jo(n.localStore, e.query,
  15027. /* usePreviousResults= */ !0), i = e.view.tc(s);
  15028. return n.isPrimaryClient && Bc(n, e.targetId, i.Xu), i;
  15029. }
  15030. /**
  15031. * Retrieves newly changed documents from remote document cache and raises
  15032. * snapshots if needed.
  15033. */
  15034. // PORTING NOTE: Multi-Tab only.
  15035. async function jc(t, e) {
  15036. const n = $(t);
  15037. return Xo(n.localStore, e).then((t => Uc(n, t)));
  15038. }
  15039. /** Applies a mutation state to an existing batch. */
  15040. // PORTING NOTE: Multi-Tab only.
  15041. async function Wc(t, e, n, s) {
  15042. const i = $(t), r = await function(t, e) {
  15043. const n = $(t), s = $(n.mutationQueue);
  15044. return n.persistence.runTransaction("Lookup mutation documents", "readonly", (t => s.Tn(t, e).next((e => e ? n.localDocuments.getDocuments(t, e) : At.resolve(null)))));
  15045. }
  15046. // PORTING NOTE: Multi-Tab only.
  15047. (i.localStore, e);
  15048. null !== r ? ("pending" === n ?
  15049. // If we are the primary client, we need to send this write to the
  15050. // backend. Secondary clients will ignore these writes since their remote
  15051. // connection is disabled.
  15052. await Ku(i.remoteStore) : "acknowledged" === n || "rejected" === n ? (
  15053. // NOTE: Both these methods are no-ops for batches that originated from
  15054. // other clients.
  15055. Mc(i, e, s || null), Oc(i, e), function(t, e) {
  15056. $($(t).mutationQueue).An(e);
  15057. }
  15058. // PORTING NOTE: Multi-Tab only.
  15059. (i.localStore, e)) : O(), await Uc(i, r)) :
  15060. // A throttled tab may not have seen the mutation before it was completed
  15061. // and removed from the mutation queue, in which case we won't have cached
  15062. // the affected documents. In this case we can safely ignore the update
  15063. // since that means we didn't apply the mutation locally at all (if we
  15064. // had, we would have cached the affected documents), and so we will just
  15065. // see any resulting document changes via normal remote document updates
  15066. // as applicable.
  15067. C("SyncEngine", "Cannot apply mutation batch with id: " + e);
  15068. }
  15069. /** Applies a query target change from a different tab. */
  15070. // PORTING NOTE: Multi-Tab only.
  15071. async function zc(t, e) {
  15072. const n = $(t);
  15073. if (ta(n), ea(n), !0 === e && !0 !== n.dc) {
  15074. // Secondary tabs only maintain Views for their local listeners and the
  15075. // Views internal state may not be 100% populated (in particular
  15076. // secondary tabs don't track syncedDocuments, the set of documents the
  15077. // server considers to be in the target). So when a secondary becomes
  15078. // primary, we need to need to make sure that all views for all targets
  15079. // match the state on disk.
  15080. const t = n.sharedClientState.getAllActiveQueryTargets(), e = await Hc(n, t.toArray());
  15081. n.dc = !0, await Zu(n.remoteStore, !0);
  15082. for (const t of e) Du(n.remoteStore, t);
  15083. } else if (!1 === e && !1 !== n.dc) {
  15084. const t = [];
  15085. let e = Promise.resolve();
  15086. n.rc.forEach(((s, i) => {
  15087. n.sharedClientState.isLocalQueryTarget(i) ? t.push(i) : e = e.then((() => (Fc(n, i),
  15088. Ho(n.localStore, i,
  15089. /*keepPersistedTargetData=*/ !0)))), Cu(n.remoteStore, i);
  15090. })), await e, await Hc(n, t),
  15091. // PORTING NOTE: Multi-Tab only.
  15092. function(t) {
  15093. const e = $(t);
  15094. e.cc.forEach(((t, n) => {
  15095. Cu(e.remoteStore, n);
  15096. })), e.ac.fs(), e.cc = new Map, e.uc = new Ge(ct.comparator);
  15097. }
  15098. /**
  15099. * Reconcile the query views of the provided query targets with the state from
  15100. * persistence. Raises snapshots for any changes that affect the local
  15101. * client and returns the updated state of all target's query data.
  15102. *
  15103. * @param syncEngine - The sync engine implementation
  15104. * @param targets - the list of targets with views that need to be recomputed
  15105. * @param transitionToPrimary - `true` iff the tab transitions from a secondary
  15106. * tab to a primary tab
  15107. */
  15108. // PORTING NOTE: Multi-Tab only.
  15109. (n), n.dc = !1, await Zu(n.remoteStore, !1);
  15110. }
  15111. }
  15112. async function Hc(t, e, n) {
  15113. const s = $(t), i = [], r = [];
  15114. for (const t of e) {
  15115. let e;
  15116. const n = s.rc.get(t);
  15117. if (n && 0 !== n.length) {
  15118. // For queries that have a local View, we fetch their current state
  15119. // from LocalStore (as the resume token and the snapshot version
  15120. // might have changed) and reconcile their views with the persisted
  15121. // state (the list of syncedDocuments may have gotten out of sync).
  15122. e = await zo(s.localStore, gn(n[0]));
  15123. for (const t of n) {
  15124. const e = s.ic.get(t), n = await Qc(s, e);
  15125. n.snapshot && r.push(n.snapshot);
  15126. }
  15127. } else {
  15128. // For queries that never executed on this client, we need to
  15129. // allocate the target in LocalStore and initialize a new View.
  15130. const n = await Yo(s.localStore, t);
  15131. e = await zo(s.localStore, n), await Pc(s, Jc(n), t,
  15132. /*current=*/ !1, e.resumeToken);
  15133. }
  15134. i.push(e);
  15135. }
  15136. return s.sc.Wo(r), i;
  15137. }
  15138. /**
  15139. * Creates a `Query` object from the specified `Target`. There is no way to
  15140. * obtain the original `Query`, so we synthesize a `Query` from the `Target`
  15141. * object.
  15142. *
  15143. * The synthesized result might be different from the original `Query`, but
  15144. * since the synthesized `Query` should return the same results as the
  15145. * original one (only the presentation of results might differ), the potential
  15146. * difference will not cause issues.
  15147. */
  15148. // PORTING NOTE: Multi-Tab only.
  15149. function Jc(t) {
  15150. return hn(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, "F" /* LimitType.First */ , t.startAt, t.endAt);
  15151. }
  15152. /** Returns the IDs of the clients that are currently active. */
  15153. // PORTING NOTE: Multi-Tab only.
  15154. function Yc(t) {
  15155. const e = $(t);
  15156. return $($(e.localStore).persistence).vi();
  15157. }
  15158. /** Applies a query target change from a different tab. */
  15159. // PORTING NOTE: Multi-Tab only.
  15160. async function Xc(t, e, n, s) {
  15161. const i = $(t);
  15162. if (i.dc)
  15163. // If we receive a target state notification via WebStorage, we are
  15164. // either already secondary or another tab has taken the primary lease.
  15165. return void C("SyncEngine", "Ignoring unexpected query state notification.");
  15166. const r = i.rc.get(e);
  15167. if (r && r.length > 0) switch (n) {
  15168. case "current":
  15169. case "not-current":
  15170. {
  15171. const t = await Xo(i.localStore, Rn(r[0])), s = bs.createSynthesizedRemoteEventForCurrentChange(e, "current" === n, Qt.EMPTY_BYTE_STRING);
  15172. await Uc(i, t, s);
  15173. break;
  15174. }
  15175. case "rejected":
  15176. await Ho(i.localStore, e,
  15177. /* keepPersistedTargetData */ !0), Fc(i, e, s);
  15178. break;
  15179. default:
  15180. O();
  15181. }
  15182. }
  15183. /** Adds or removes Watch targets for queries from different tabs. */ async function Zc(t, e, n) {
  15184. const s = ta(t);
  15185. if (s.dc) {
  15186. for (const t of e) {
  15187. if (s.rc.has(t)) {
  15188. // A target might have been added in a previous attempt
  15189. C("SyncEngine", "Adding an already active target " + t);
  15190. continue;
  15191. }
  15192. const e = await Yo(s.localStore, t), n = await zo(s.localStore, e);
  15193. await Pc(s, Jc(e), n.targetId,
  15194. /*current=*/ !1, n.resumeToken), Du(s.remoteStore, n);
  15195. }
  15196. for (const t of n)
  15197. // Check that the target is still active since the target might have been
  15198. // removed if it has been rejected by the backend.
  15199. s.rc.has(t) &&
  15200. // Release queries that are still active.
  15201. await Ho(s.localStore, t,
  15202. /* keepPersistedTargetData */ !1).then((() => {
  15203. Cu(s.remoteStore, t), Fc(s, t);
  15204. })).catch(Et);
  15205. }
  15206. }
  15207. function ta(t) {
  15208. const e = $(t);
  15209. return e.remoteStore.remoteSyncer.applyRemoteEvent = Sc.bind(null, e), e.remoteStore.remoteSyncer.getRemoteKeysForTarget = Gc.bind(null, e),
  15210. e.remoteStore.remoteSyncer.rejectListen = Cc.bind(null, e), e.sc.Wo = lc.bind(null, e.eventManager),
  15211. e.sc.wc = fc.bind(null, e.eventManager), e;
  15212. }
  15213. function ea(t) {
  15214. const e = $(t);
  15215. return e.remoteStore.remoteSyncer.applySuccessfulWrite = xc.bind(null, e), e.remoteStore.remoteSyncer.rejectFailedWrite = Nc.bind(null, e),
  15216. e;
  15217. }
  15218. /**
  15219. * Loads a Firestore bundle into the SDK. The returned promise resolves when
  15220. * the bundle finished loading.
  15221. *
  15222. * @param syncEngine - SyncEngine to use.
  15223. * @param bundleReader - Bundle to load into the SDK.
  15224. * @param task - LoadBundleTask used to update the loading progress to public API.
  15225. */ function na(t, e, n) {
  15226. const s = $(t);
  15227. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  15228. (
  15229. /** Loads a bundle and returns the list of affected collection groups. */
  15230. async function(t, e, n) {
  15231. try {
  15232. const s = await e.getMetadata();
  15233. if (await function(t, e) {
  15234. const n = $(t), s = qs(e.createTime);
  15235. return n.persistence.runTransaction("hasNewerBundle", "readonly", (t => n.Ns.getBundleMetadata(t, e.id))).then((t => !!t && t.createTime.compareTo(s) >= 0));
  15236. }
  15237. /**
  15238. * Saves the given `BundleMetadata` to local persistence.
  15239. */ (t.localStore, s)) return await e.close(), n._completeWith(function(t) {
  15240. return {
  15241. taskState: "Success",
  15242. documentsLoaded: t.totalDocuments,
  15243. bytesLoaded: t.totalBytes,
  15244. totalDocuments: t.totalDocuments,
  15245. totalBytes: t.totalBytes
  15246. };
  15247. }(s)), Promise.resolve(new Set);
  15248. n._updateProgress(yc(s));
  15249. const i = new gc(s, t.localStore, e.yt);
  15250. let r = await e.mc();
  15251. for (;r; ) {
  15252. const t = await i.Fu(r);
  15253. t && n._updateProgress(t), r = await e.mc();
  15254. }
  15255. const o = await i.complete();
  15256. return await Uc(t, o.Lu,
  15257. /* remoteEvent */ void 0),
  15258. // Save metadata, so loading the same bundle will skip.
  15259. await function(t, e) {
  15260. const n = $(t);
  15261. return n.persistence.runTransaction("Save bundle", "readwrite", (t => n.Ns.saveBundleMetadata(t, e)));
  15262. }
  15263. /**
  15264. * Returns a promise of a `NamedQuery` associated with given query name. Promise
  15265. * resolves to undefined if no persisted data can be found.
  15266. */ (t.localStore, s), n._completeWith(o.progress), Promise.resolve(o.Bu);
  15267. } catch (t) {
  15268. return N("SyncEngine", `Loading bundle failed with ${t}`), n._failWith(t), Promise.resolve(new Set);
  15269. }
  15270. }
  15271. /**
  15272. * @license
  15273. * Copyright 2020 Google LLC
  15274. *
  15275. * Licensed under the Apache License, Version 2.0 (the "License");
  15276. * you may not use this file except in compliance with the License.
  15277. * You may obtain a copy of the License at
  15278. *
  15279. * http://www.apache.org/licenses/LICENSE-2.0
  15280. *
  15281. * Unless required by applicable law or agreed to in writing, software
  15282. * distributed under the License is distributed on an "AS IS" BASIS,
  15283. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15284. * See the License for the specific language governing permissions and
  15285. * limitations under the License.
  15286. */
  15287. /**
  15288. * Provides all components needed for Firestore with in-memory persistence.
  15289. * Uses EagerGC garbage collection.
  15290. */)(s, e, n).then((t => {
  15291. s.sharedClientState.notifyBundleLoaded(t);
  15292. }));
  15293. }
  15294. class sa {
  15295. constructor() {
  15296. this.synchronizeTabs = !1;
  15297. }
  15298. async initialize(t) {
  15299. this.yt = pu(t.databaseInfo.databaseId), this.sharedClientState = this.gc(t), this.persistence = this.yc(t),
  15300. await this.persistence.start(), this.localStore = this.Ic(t), this.gcScheduler = this.Tc(t, this.localStore),
  15301. this.indexBackfillerScheduler = this.Ec(t, this.localStore);
  15302. }
  15303. Tc(t, e) {
  15304. return null;
  15305. }
  15306. Ec(t, e) {
  15307. return null;
  15308. }
  15309. Ic(t) {
  15310. return qo(this.persistence, new Bo, t.initialUser, this.yt);
  15311. }
  15312. yc(t) {
  15313. return new Vo(Do.Bs, this.yt);
  15314. }
  15315. gc(t) {
  15316. return new lu;
  15317. }
  15318. async terminate() {
  15319. this.gcScheduler && this.gcScheduler.stop(), await this.sharedClientState.shutdown(),
  15320. await this.persistence.shutdown();
  15321. }
  15322. }
  15323. /**
  15324. * Provides all components needed for Firestore with IndexedDB persistence.
  15325. */ class ia extends sa {
  15326. constructor(t, e, n) {
  15327. super(), this.Ac = t, this.cacheSizeBytes = e, this.forceOwnership = n, this.synchronizeTabs = !1;
  15328. }
  15329. async initialize(t) {
  15330. await super.initialize(t), await this.Ac.initialize(this, t),
  15331. // Enqueue writes from a previous session
  15332. await ea(this.Ac.syncEngine), await Ku(this.Ac.remoteStore),
  15333. // NOTE: This will immediately call the listener, so we make sure to
  15334. // set it after localStore / remoteStore are started.
  15335. await this.persistence.li((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(),
  15336. this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(),
  15337. Promise.resolve())));
  15338. }
  15339. Ic(t) {
  15340. return qo(this.persistence, new Bo, t.initialUser, this.yt);
  15341. }
  15342. Tc(t, e) {
  15343. const n = this.persistence.referenceDelegate.garbageCollector;
  15344. return new io(n, t.asyncQueue, e);
  15345. }
  15346. Ec(t, e) {
  15347. const n = new kt(e, this.persistence);
  15348. return new Nt(t.asyncQueue, n);
  15349. }
  15350. yc(t) {
  15351. const e = Fo(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? Kr.withCacheSize(this.cacheSizeBytes) : Kr.DEFAULT;
  15352. return new ko(this.synchronizeTabs, e, t.clientId, n, t.asyncQueue, gu(), yu(), this.yt, this.sharedClientState, !!this.forceOwnership);
  15353. }
  15354. gc(t) {
  15355. return new lu;
  15356. }
  15357. }
  15358. /**
  15359. * Provides all components needed for Firestore with multi-tab IndexedDB
  15360. * persistence.
  15361. *
  15362. * In the legacy client, this provider is used to provide both multi-tab and
  15363. * non-multi-tab persistence since we cannot tell at build time whether
  15364. * `synchronizeTabs` will be enabled.
  15365. */ class ra extends ia {
  15366. constructor(t, e) {
  15367. super(t, e, /* forceOwnership= */ !1), this.Ac = t, this.cacheSizeBytes = e, this.synchronizeTabs = !0;
  15368. }
  15369. async initialize(t) {
  15370. await super.initialize(t);
  15371. const e = this.Ac.syncEngine;
  15372. this.sharedClientState instanceof hu && (this.sharedClientState.syncEngine = {
  15373. Fr: Wc.bind(null, e),
  15374. $r: Xc.bind(null, e),
  15375. Br: Zc.bind(null, e),
  15376. vi: Yc.bind(null, e),
  15377. Mr: jc.bind(null, e)
  15378. }, await this.sharedClientState.start()),
  15379. // NOTE: This will immediately call the listener, so we make sure to
  15380. // set it after localStore / remoteStore are started.
  15381. await this.persistence.li((async t => {
  15382. await zc(this.Ac.syncEngine, t), this.gcScheduler && (t && !this.gcScheduler.started ? this.gcScheduler.start() : t || this.gcScheduler.stop()),
  15383. this.indexBackfillerScheduler && (t && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : t || this.indexBackfillerScheduler.stop());
  15384. }));
  15385. }
  15386. gc(t) {
  15387. const e = gu();
  15388. if (!hu.C(e)) throw new L(B.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
  15389. const n = Fo(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey);
  15390. return new hu(e, t.asyncQueue, n, t.clientId, t.initialUser);
  15391. }
  15392. }
  15393. /**
  15394. * Initializes and wires the components that are needed to interface with the
  15395. * network.
  15396. */ class oa {
  15397. async initialize(t, e) {
  15398. this.localStore || (this.localStore = t.localStore, this.sharedClientState = t.sharedClientState,
  15399. this.datastore = this.createDatastore(e), this.remoteStore = this.createRemoteStore(e),
  15400. this.eventManager = this.createEventManager(e), this.syncEngine = this.createSyncEngine(e,
  15401. /* startAsPrimary=*/ !t.synchronizeTabs), this.sharedClientState.onlineStateHandler = t => Dc(this.syncEngine, t, 1 /* OnlineStateSource.SharedClientState */),
  15402. this.remoteStore.remoteSyncer.handleCredentialChange = Kc.bind(null, this.syncEngine),
  15403. await Zu(this.remoteStore, this.syncEngine.isPrimaryClient));
  15404. }
  15405. createEventManager(t) {
  15406. return new cc;
  15407. }
  15408. createDatastore(t) {
  15409. const e = pu(t.databaseInfo.databaseId), n = (s = t.databaseInfo, new mu(s));
  15410. var s;
  15411. /** Return the Platform-specific connectivity monitor. */ return function(t, e, n, s) {
  15412. return new Ru(t, e, n, s);
  15413. }(t.authCredentials, t.appCheckCredentials, n, e);
  15414. }
  15415. createRemoteStore(t) {
  15416. return e = this.localStore, n = this.datastore, s = t.asyncQueue, i = t => Dc(this.syncEngine, t, 0 /* OnlineStateSource.RemoteStore */),
  15417. r = du.C() ? new du : new fu, new vu(e, n, s, i, r);
  15418. var e, n, s, i, r;
  15419. /** Re-enables the network. Idempotent. */ }
  15420. createSyncEngine(t, e) {
  15421. return function(t, e, n,
  15422. // PORTING NOTE: Manages state synchronization in multi-tab environments.
  15423. s, i, r, o) {
  15424. const u = new Rc(t, e, n, s, i, r);
  15425. return o && (u.dc = !0), u;
  15426. }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, t.initialUser, t.maxConcurrentLimboResolutions, e);
  15427. }
  15428. terminate() {
  15429. return async function(t) {
  15430. const e = $(t);
  15431. C("RemoteStore", "RemoteStore shutting down."), e._u.add(5 /* OfflineCause.Shutdown */),
  15432. await Su(e), e.mu.shutdown(),
  15433. // Set the OnlineState to Unknown (rather than Offline) to avoid potentially
  15434. // triggering spurious listener events with cached data, etc.
  15435. e.gu.set("Unknown" /* OnlineState.Unknown */);
  15436. }(this.remoteStore);
  15437. }
  15438. }
  15439. /**
  15440. * @license
  15441. * Copyright 2017 Google LLC
  15442. *
  15443. * Licensed under the Apache License, Version 2.0 (the "License");
  15444. * you may not use this file except in compliance with the License.
  15445. * You may obtain a copy of the License at
  15446. *
  15447. * http://www.apache.org/licenses/LICENSE-2.0
  15448. *
  15449. * Unless required by applicable law or agreed to in writing, software
  15450. * distributed under the License is distributed on an "AS IS" BASIS,
  15451. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15452. * See the License for the specific language governing permissions and
  15453. * limitations under the License.
  15454. */ function ua(t, e, n) {
  15455. if (!n) throw new L(B.INVALID_ARGUMENT, `Function ${t}() cannot be called with an empty ${e}.`);
  15456. }
  15457. /**
  15458. * Validates that two boolean options are not set at the same time.
  15459. * @internal
  15460. */ function ca(t, e, n, s) {
  15461. if (!0 === e && !0 === s) throw new L(B.INVALID_ARGUMENT, `${t} and ${n} cannot be used together.`);
  15462. }
  15463. /**
  15464. * Validates that `path` refers to a document (indicated by the fact it contains
  15465. * an even numbers of segments).
  15466. */ function aa(t) {
  15467. if (!ct.isDocumentKey(t)) throw new L(B.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`);
  15468. }
  15469. /**
  15470. * Validates that `path` refers to a collection (indicated by the fact it
  15471. * contains an odd numbers of segments).
  15472. */ function ha(t) {
  15473. if (ct.isDocumentKey(t)) throw new L(B.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`);
  15474. }
  15475. /**
  15476. * Returns true if it's a non-null object without a custom prototype
  15477. * (i.e. excludes Array, Date, etc.).
  15478. */
  15479. /** Returns a string describing the type / value of the provided input. */
  15480. function la(t) {
  15481. if (void 0 === t) return "undefined";
  15482. if (null === t) return "null";
  15483. if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`),
  15484. JSON.stringify(t);
  15485. if ("number" == typeof t || "boolean" == typeof t) return "" + t;
  15486. if ("object" == typeof t) {
  15487. if (t instanceof Array) return "an array";
  15488. {
  15489. const e =
  15490. /** try to get the constructor name for an object. */
  15491. function(t) {
  15492. if (t.constructor) return t.constructor.name;
  15493. return null;
  15494. }
  15495. /**
  15496. * Casts `obj` to `T`, optionally unwrapping Compat types to expose the
  15497. * underlying instance. Throws if `obj` is not an instance of `T`.
  15498. *
  15499. * This cast is used in the Lite and Full SDK to verify instance types for
  15500. * arguments passed to the public API.
  15501. * @internal
  15502. */ (t);
  15503. return e ? `a custom ${e} object` : "an object";
  15504. }
  15505. }
  15506. return "function" == typeof t ? "a function" : O();
  15507. }
  15508. function fa(t,
  15509. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15510. e) {
  15511. if ("_delegate" in t && (
  15512. // Unwrap Compat types
  15513. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15514. t = t._delegate), !(t instanceof e)) {
  15515. if (e.name === t.constructor.name) throw new L(B.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
  15516. {
  15517. const n = la(t);
  15518. throw new L(B.INVALID_ARGUMENT, `Expected type '${e.name}', but it was: ${n}`);
  15519. }
  15520. }
  15521. return t;
  15522. }
  15523. function da(t, e) {
  15524. if (e <= 0) throw new L(B.INVALID_ARGUMENT, `Function ${t}() requires a positive number, but it was: ${e}.`);
  15525. }
  15526. /**
  15527. * @license
  15528. * Copyright 2020 Google LLC
  15529. *
  15530. * Licensed under the Apache License, Version 2.0 (the "License");
  15531. * you may not use this file except in compliance with the License.
  15532. * You may obtain a copy of the License at
  15533. *
  15534. * http://www.apache.org/licenses/LICENSE-2.0
  15535. *
  15536. * Unless required by applicable law or agreed to in writing, software
  15537. * distributed under the License is distributed on an "AS IS" BASIS,
  15538. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15539. * See the License for the specific language governing permissions and
  15540. * limitations under the License.
  15541. */ const _a = new Map;
  15542. /**
  15543. * An instance map that ensures only one Datastore exists per Firestore
  15544. * instance.
  15545. */
  15546. /**
  15547. * A concrete type describing all the values that can be applied via a
  15548. * user-supplied `FirestoreSettings` object. This is a separate type so that
  15549. * defaults can be supplied and the value can be checked for equality.
  15550. */
  15551. class wa {
  15552. constructor(t) {
  15553. var e;
  15554. if (void 0 === t.host) {
  15555. if (void 0 !== t.ssl) throw new L(B.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
  15556. this.host = "firestore.googleapis.com", this.ssl = true;
  15557. } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;
  15558. if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties,
  15559. void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {
  15560. if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new L(B.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  15561. this.cacheSizeBytes = t.cacheSizeBytes;
  15562. }
  15563. this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling,
  15564. this.useFetchStreams = !!t.useFetchStreams, ca("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling);
  15565. }
  15566. isEqual(t) {
  15567. 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;
  15568. }
  15569. }
  15570. /**
  15571. * @license
  15572. * Copyright 2020 Google LLC
  15573. *
  15574. * Licensed under the Apache License, Version 2.0 (the "License");
  15575. * you may not use this file except in compliance with the License.
  15576. * You may obtain a copy of the License at
  15577. *
  15578. * http://www.apache.org/licenses/LICENSE-2.0
  15579. *
  15580. * Unless required by applicable law or agreed to in writing, software
  15581. * distributed under the License is distributed on an "AS IS" BASIS,
  15582. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15583. * See the License for the specific language governing permissions and
  15584. * limitations under the License.
  15585. */
  15586. /**
  15587. * The Cloud Firestore service interface.
  15588. *
  15589. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  15590. */ class ma {
  15591. /** @hideconstructor */
  15592. constructor(t, e, n, s) {
  15593. this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = n,
  15594. this._app = s,
  15595. /**
  15596. * Whether it's a Firestore or Firestore Lite instance.
  15597. */
  15598. this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new wa({}),
  15599. this._settingsFrozen = !1;
  15600. }
  15601. /**
  15602. * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
  15603. * instance.
  15604. */ get app() {
  15605. if (!this._app) throw new L(B.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
  15606. return this._app;
  15607. }
  15608. get _initialized() {
  15609. return this._settingsFrozen;
  15610. }
  15611. get _terminated() {
  15612. return void 0 !== this._terminateTask;
  15613. }
  15614. _setSettings(t) {
  15615. if (this._settingsFrozen) throw new L(B.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.");
  15616. this._settings = new wa(t), void 0 !== t.credentials && (this._authCredentials = function(t) {
  15617. if (!t) return new K;
  15618. switch (t.type) {
  15619. case "gapi":
  15620. const e = t.client;
  15621. return new W(e, t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null);
  15622. case "provider":
  15623. return t.client;
  15624. default:
  15625. throw new L(B.INVALID_ARGUMENT, "makeAuthCredentialsProvider failed due to invalid credential type");
  15626. }
  15627. }(t.credentials));
  15628. }
  15629. _getSettings() {
  15630. return this._settings;
  15631. }
  15632. _freezeSettings() {
  15633. return this._settingsFrozen = !0, this._settings;
  15634. }
  15635. _delete() {
  15636. return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;
  15637. }
  15638. /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() {
  15639. return {
  15640. app: this._app,
  15641. databaseId: this._databaseId,
  15642. settings: this._settings
  15643. };
  15644. }
  15645. /**
  15646. * Terminates all components used by this client. Subclasses can override
  15647. * this method to clean up their own dependencies, but must also call this
  15648. * method.
  15649. *
  15650. * Only ever called once.
  15651. */ _terminate() {
  15652. /**
  15653. * Removes all components associated with the provided instance. Must be called
  15654. * when the `Firestore` instance is terminated.
  15655. */
  15656. return function(t) {
  15657. const e = _a.get(t);
  15658. e && (C("ComponentProvider", "Removing Datastore"), _a.delete(t), e.terminate());
  15659. }(this), Promise.resolve();
  15660. }
  15661. }
  15662. /**
  15663. * Modify this instance to communicate with the Cloud Firestore emulator.
  15664. *
  15665. * Note: This must be called before this instance has been used to do any
  15666. * operations.
  15667. *
  15668. * @param firestore - The `Firestore` instance to configure to connect to the
  15669. * emulator.
  15670. * @param host - the emulator host (ex: localhost).
  15671. * @param port - the emulator port (ex: 9000).
  15672. * @param options.mockUserToken - the mock auth token to use for unit testing
  15673. * Security Rules.
  15674. */ function ga(t, e, n, s = {}) {
  15675. var i;
  15676. const r = (t = fa(t, ma))._getSettings();
  15677. if ("firestore.googleapis.com" !== r.host && r.host !== e && N("Host has been set in both settings() and useEmulator(), emulator host will be used"),
  15678. t._setSettings(Object.assign(Object.assign({}, r), {
  15679. host: `${e}:${n}`,
  15680. ssl: !1
  15681. })), s.mockUserToken) {
  15682. let e, n;
  15683. if ("string" == typeof s.mockUserToken) e = s.mockUserToken, n = P.MOCK_USER; else {
  15684. // Let createMockUserToken validate first (catches common mistakes like
  15685. // invalid field "uid" and missing field "sub" / "user_id".)
  15686. e = createMockUserToken(s.mockUserToken, null === (i = t._app) || void 0 === i ? void 0 : i.options.projectId);
  15687. const r = s.mockUserToken.sub || s.mockUserToken.user_id;
  15688. if (!r) throw new L(B.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!");
  15689. n = new P(r);
  15690. }
  15691. t._authCredentials = new G(new U(e, n));
  15692. }
  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. */
  15710. /**
  15711. * A `DocumentReference` refers to a document location in a Firestore database
  15712. * and can be used to write, read, or listen to the location. The document at
  15713. * the referenced location may or may not exist.
  15714. */ class ya {
  15715. /** @hideconstructor */
  15716. constructor(t,
  15717. /**
  15718. * If provided, the `FirestoreDataConverter` associated with this instance.
  15719. */
  15720. e, n) {
  15721. this.converter = e, this._key = n,
  15722. /** The type of this Firestore reference. */
  15723. this.type = "document", this.firestore = t;
  15724. }
  15725. get _path() {
  15726. return this._key.path;
  15727. }
  15728. /**
  15729. * The document's identifier within its collection.
  15730. */ get id() {
  15731. return this._key.path.lastSegment();
  15732. }
  15733. /**
  15734. * A string representing the path of the referenced document (relative
  15735. * to the root of the database).
  15736. */ get path() {
  15737. return this._key.path.canonicalString();
  15738. }
  15739. /**
  15740. * The collection this `DocumentReference` belongs to.
  15741. */ get parent() {
  15742. return new Ia(this.firestore, this.converter, this._key.path.popLast());
  15743. }
  15744. withConverter(t) {
  15745. return new ya(this.firestore, t, this._key);
  15746. }
  15747. }
  15748. /**
  15749. * A `Query` refers to a query which you can read or listen to. You can also
  15750. * construct refined `Query` objects by adding filters and ordering.
  15751. */ class pa {
  15752. // This is the lite version of the Query class in the main SDK.
  15753. /** @hideconstructor protected */
  15754. constructor(t,
  15755. /**
  15756. * If provided, the `FirestoreDataConverter` associated with this instance.
  15757. */
  15758. e, n) {
  15759. this.converter = e, this._query = n,
  15760. /** The type of this Firestore reference. */
  15761. this.type = "query", this.firestore = t;
  15762. }
  15763. withConverter(t) {
  15764. return new pa(this.firestore, t, this._query);
  15765. }
  15766. }
  15767. /**
  15768. * A `CollectionReference` object can be used for adding documents, getting
  15769. * document references, and querying for documents (using {@link query}).
  15770. */ class Ia extends pa {
  15771. /** @hideconstructor */
  15772. constructor(t, e, n) {
  15773. super(t, e, ln(n)), this._path = n,
  15774. /** The type of this Firestore reference. */
  15775. this.type = "collection";
  15776. }
  15777. /** The collection's identifier. */ get id() {
  15778. return this._query.path.lastSegment();
  15779. }
  15780. /**
  15781. * A string representing the path of the referenced collection (relative
  15782. * to the root of the database).
  15783. */ get path() {
  15784. return this._query.path.canonicalString();
  15785. }
  15786. /**
  15787. * A reference to the containing `DocumentReference` if this is a
  15788. * subcollection. If this isn't a subcollection, the reference is null.
  15789. */ get parent() {
  15790. const t = this._path.popLast();
  15791. return t.isEmpty() ? null : new ya(this.firestore,
  15792. /* converter= */ null, new ct(t));
  15793. }
  15794. withConverter(t) {
  15795. return new Ia(this.firestore, t, this._path);
  15796. }
  15797. }
  15798. function Ta(t, e, ...n) {
  15799. if (t = getModularInstance(t), ua("collection", "path", e), t instanceof ma) {
  15800. const s = rt.fromString(e, ...n);
  15801. return ha(s), new Ia(t, /* converter= */ null, s);
  15802. }
  15803. {
  15804. if (!(t instanceof ya || t instanceof Ia)) throw new L(B.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  15805. const s = t._path.child(rt.fromString(e, ...n));
  15806. return ha(s), new Ia(t.firestore,
  15807. /* converter= */ null, s);
  15808. }
  15809. }
  15810. // TODO(firestorelite): Consider using ErrorFactory -
  15811. // https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106
  15812. /**
  15813. * Creates and returns a new `Query` instance that includes all documents in the
  15814. * database that are contained in a collection or subcollection with the
  15815. * given `collectionId`.
  15816. *
  15817. * @param firestore - A reference to the root `Firestore` instance.
  15818. * @param collectionId - Identifies the collections to query over. Every
  15819. * collection or subcollection with this ID as the last segment of its path
  15820. * will be included. Cannot contain a slash.
  15821. * @returns The created `Query`.
  15822. */ function Ea(t, e) {
  15823. if (t = fa(t, ma), ua("collectionGroup", "collection id", e), e.indexOf("/") >= 0) throw new L(B.INVALID_ARGUMENT, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);
  15824. return new pa(t,
  15825. /* converter= */ null, function(t) {
  15826. return new an(rt.emptyPath(), t);
  15827. }(e));
  15828. }
  15829. function Aa(t, e, ...n) {
  15830. if (t = getModularInstance(t),
  15831. // We allow omission of 'pathString' but explicitly prohibit passing in both
  15832. // 'undefined' and 'null'.
  15833. 1 === arguments.length && (e = X.R()), ua("doc", "path", e), t instanceof ma) {
  15834. const s = rt.fromString(e, ...n);
  15835. return aa(s), new ya(t,
  15836. /* converter= */ null, new ct(s));
  15837. }
  15838. {
  15839. if (!(t instanceof ya || t instanceof Ia)) throw new L(B.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
  15840. const s = t._path.child(rt.fromString(e, ...n));
  15841. return aa(s), new ya(t.firestore, t instanceof Ia ? t.converter : null, new ct(s));
  15842. }
  15843. }
  15844. /**
  15845. * Returns true if the provided references are equal.
  15846. *
  15847. * @param left - A reference to compare.
  15848. * @param right - A reference to compare.
  15849. * @returns true if the references point to the same location in the same
  15850. * Firestore database.
  15851. */ function Ra(t, e) {
  15852. return t = getModularInstance(t), e = getModularInstance(e), (t instanceof ya || t instanceof Ia) && (e instanceof ya || e instanceof Ia) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter);
  15853. }
  15854. /**
  15855. * Returns true if the provided queries point to the same collection and apply
  15856. * the same constraints.
  15857. *
  15858. * @param left - A `Query` to compare.
  15859. * @param right - A `Query` to compare.
  15860. * @returns true if the references point to the same location in the same
  15861. * Firestore database.
  15862. */ function ba(t, e) {
  15863. return t = getModularInstance(t), e = getModularInstance(e), t instanceof pa && e instanceof pa && (t.firestore === e.firestore && In(t._query, e._query) && t.converter === e.converter);
  15864. }
  15865. /**
  15866. * @license
  15867. * Copyright 2020 Google LLC
  15868. *
  15869. * Licensed under the Apache License, Version 2.0 (the "License");
  15870. * you may not use this file except in compliance with the License.
  15871. * You may obtain a copy of the License at
  15872. *
  15873. * http://www.apache.org/licenses/LICENSE-2.0
  15874. *
  15875. * Unless required by applicable law or agreed to in writing, software
  15876. * distributed under the License is distributed on an "AS IS" BASIS,
  15877. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15878. * See the License for the specific language governing permissions and
  15879. * limitations under the License.
  15880. */
  15881. /**
  15882. * How many bytes to read each time when `ReadableStreamReader.read()` is
  15883. * called. Only applicable for byte streams that we control (e.g. those backed
  15884. * by an UInt8Array).
  15885. */
  15886. /**
  15887. * Builds a `ByteStreamReader` from a UInt8Array.
  15888. * @param source - The data source to use.
  15889. * @param bytesPerRead - How many bytes each `read()` from the returned reader
  15890. * will read.
  15891. */
  15892. function Pa(t, e = 10240) {
  15893. let n = 0;
  15894. // The TypeScript definition for ReadableStreamReader changed. We use
  15895. // `any` here to allow this code to compile with different versions.
  15896. // See https://github.com/microsoft/TypeScript/issues/42970
  15897. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15898. return {
  15899. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  15900. async read() {
  15901. if (n < t.byteLength) {
  15902. const s = {
  15903. value: t.slice(n, n + e),
  15904. done: !1
  15905. };
  15906. return n += e, s;
  15907. }
  15908. return {
  15909. done: !0
  15910. };
  15911. },
  15912. async cancel() {},
  15913. releaseLock() {},
  15914. closed: Promise.reject("unimplemented")
  15915. };
  15916. }
  15917. /**
  15918. * @license
  15919. * Copyright 2020 Google LLC
  15920. *
  15921. * Licensed under the Apache License, Version 2.0 (the "License");
  15922. * you may not use this file except in compliance with the License.
  15923. * You may obtain a copy of the License at
  15924. *
  15925. * http://www.apache.org/licenses/LICENSE-2.0
  15926. *
  15927. * Unless required by applicable law or agreed to in writing, software
  15928. * distributed under the License is distributed on an "AS IS" BASIS,
  15929. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15930. * See the License for the specific language governing permissions and
  15931. * limitations under the License.
  15932. */
  15933. /**
  15934. * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.
  15935. */
  15936. /**
  15937. * @license
  15938. * Copyright 2017 Google LLC
  15939. *
  15940. * Licensed under the Apache License, Version 2.0 (the "License");
  15941. * you may not use this file except in compliance with the License.
  15942. * You may obtain a copy of the License at
  15943. *
  15944. * http://www.apache.org/licenses/LICENSE-2.0
  15945. *
  15946. * Unless required by applicable law or agreed to in writing, software
  15947. * distributed under the License is distributed on an "AS IS" BASIS,
  15948. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15949. * See the License for the specific language governing permissions and
  15950. * limitations under the License.
  15951. */
  15952. /*
  15953. * A wrapper implementation of Observer<T> that will dispatch events
  15954. * asynchronously. To allow immediate silencing, a mute call is added which
  15955. * causes events scheduled to no longer be raised.
  15956. */
  15957. class va {
  15958. constructor(t) {
  15959. this.observer = t,
  15960. /**
  15961. * When set to true, will not raise future events. Necessary to deal with
  15962. * async detachment of listener.
  15963. */
  15964. this.muted = !1;
  15965. }
  15966. next(t) {
  15967. this.observer.next && this.Rc(this.observer.next, t);
  15968. }
  15969. error(t) {
  15970. this.observer.error ? this.Rc(this.observer.error, t) : x("Uncaught Error in snapshot listener:", t.toString());
  15971. }
  15972. bc() {
  15973. this.muted = !0;
  15974. }
  15975. Rc(t, e) {
  15976. this.muted || setTimeout((() => {
  15977. this.muted || t(e);
  15978. }), 0);
  15979. }
  15980. }
  15981. /**
  15982. * @license
  15983. * Copyright 2020 Google LLC
  15984. *
  15985. * Licensed under the Apache License, Version 2.0 (the "License");
  15986. * you may not use this file except in compliance with the License.
  15987. * You may obtain a copy of the License at
  15988. *
  15989. * http://www.apache.org/licenses/LICENSE-2.0
  15990. *
  15991. * Unless required by applicable law or agreed to in writing, software
  15992. * distributed under the License is distributed on an "AS IS" BASIS,
  15993. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15994. * See the License for the specific language governing permissions and
  15995. * limitations under the License.
  15996. */
  15997. /**
  15998. * A class representing a bundle.
  15999. *
  16000. * Takes a bundle stream or buffer, and presents abstractions to read bundled
  16001. * elements out of the underlying content.
  16002. */ class Va {
  16003. constructor(
  16004. /** The reader to read from underlying binary bundle data source. */
  16005. t, e) {
  16006. this.Pc = t, this.yt = e,
  16007. /** Cached bundle metadata. */
  16008. this.metadata = new q,
  16009. /**
  16010. * Internal buffer to hold bundle content, accumulating incomplete element
  16011. * content.
  16012. */
  16013. this.buffer = new Uint8Array, this.vc = new TextDecoder("utf-8"),
  16014. // Read the metadata (which is the first element).
  16015. this.Vc().then((t => {
  16016. t && t.Ou() ? this.metadata.resolve(t.ku.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null == t ? void 0 : t.ku)}`));
  16017. }), (t => this.metadata.reject(t)));
  16018. }
  16019. close() {
  16020. return this.Pc.cancel();
  16021. }
  16022. async getMetadata() {
  16023. return this.metadata.promise;
  16024. }
  16025. async mc() {
  16026. // Makes sure metadata is read before proceeding.
  16027. return await this.getMetadata(), this.Vc();
  16028. }
  16029. /**
  16030. * Reads from the head of internal buffer, and pulling more data from
  16031. * underlying stream if a complete element cannot be found, until an
  16032. * element(including the prefixed length and the JSON string) is found.
  16033. *
  16034. * Once a complete element is read, it is dropped from internal buffer.
  16035. *
  16036. * Returns either the bundled element, or null if we have reached the end of
  16037. * the stream.
  16038. */ async Vc() {
  16039. const t = await this.Sc();
  16040. if (null === t) return null;
  16041. const e = this.vc.decode(t), n = Number(e);
  16042. isNaN(n) && this.Dc(`length string (${e}) is not valid number`);
  16043. const s = await this.Cc(n);
  16044. return new wc(JSON.parse(s), t.length + n);
  16045. }
  16046. /** First index of '{' from the underlying buffer. */ xc() {
  16047. return this.buffer.findIndex((t => t === "{".charCodeAt(0)));
  16048. }
  16049. /**
  16050. * Reads from the beginning of the internal buffer, until the first '{', and
  16051. * return the content.
  16052. *
  16053. * If reached end of the stream, returns a null.
  16054. */ async Sc() {
  16055. for (;this.xc() < 0; ) {
  16056. if (await this.Nc()) break;
  16057. }
  16058. // Broke out of the loop because underlying stream is closed, and there
  16059. // happens to be no more data to process.
  16060. if (0 === this.buffer.length) return null;
  16061. const t = this.xc();
  16062. // Broke out of the loop because underlying stream is closed, but still
  16063. // cannot find an open bracket.
  16064. t < 0 && this.Dc("Reached the end of bundle when a length string is expected.");
  16065. const e = this.buffer.slice(0, t);
  16066. // Update the internal buffer to drop the read length.
  16067. return this.buffer = this.buffer.slice(t), e;
  16068. }
  16069. /**
  16070. * Reads from a specified position from the internal buffer, for a specified
  16071. * number of bytes, pulling more data from the underlying stream if needed.
  16072. *
  16073. * Returns a string decoded from the read bytes.
  16074. */ async Cc(t) {
  16075. for (;this.buffer.length < t; ) {
  16076. await this.Nc() && this.Dc("Reached the end of bundle when more is expected.");
  16077. }
  16078. const e = this.vc.decode(this.buffer.slice(0, t));
  16079. // Update the internal buffer to drop the read json string.
  16080. return this.buffer = this.buffer.slice(t), e;
  16081. }
  16082. Dc(t) {
  16083. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  16084. throw this.Pc.cancel(), new Error(`Invalid bundle format: ${t}`);
  16085. }
  16086. /**
  16087. * Pulls more data from underlying stream to internal buffer.
  16088. * Returns a boolean indicating whether the stream is finished.
  16089. */ async Nc() {
  16090. const t = await this.Pc.read();
  16091. if (!t.done) {
  16092. const e = new Uint8Array(this.buffer.length + t.value.length);
  16093. e.set(this.buffer), e.set(t.value, this.buffer.length), this.buffer = e;
  16094. }
  16095. return t.done;
  16096. }
  16097. }
  16098. /**
  16099. * @license
  16100. * Copyright 2022 Google LLC
  16101. *
  16102. * Licensed under the Apache License, Version 2.0 (the "License");
  16103. * you may not use this file except in compliance with the License.
  16104. * You may obtain a copy of the License at
  16105. *
  16106. * http://www.apache.org/licenses/LICENSE-2.0
  16107. *
  16108. * Unless required by applicable law or agreed to in writing, software
  16109. * distributed under the License is distributed on an "AS IS" BASIS,
  16110. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16111. * See the License for the specific language governing permissions and
  16112. * limitations under the License.
  16113. */
  16114. /**
  16115. * Represents an aggregation that can be performed by Firestore.
  16116. */
  16117. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  16118. class Sa {
  16119. constructor() {
  16120. /** A type string to uniquely identify instances of this class. */
  16121. this.type = "AggregateField";
  16122. }
  16123. }
  16124. /**
  16125. * The results of executing an aggregation query.
  16126. */ class Da {
  16127. /** @hideconstructor */
  16128. constructor(t, e) {
  16129. this._data = e,
  16130. /** A type string to uniquely identify instances of this class. */
  16131. this.type = "AggregateQuerySnapshot", this.query = t;
  16132. }
  16133. /**
  16134. * Returns the results of the aggregations performed over the underlying
  16135. * query.
  16136. *
  16137. * The keys of the returned object will be the same as those of the
  16138. * `AggregateSpec` object specified to the aggregation method, and the values
  16139. * will be the corresponding aggregation result.
  16140. *
  16141. * @returns The results of the aggregations performed over the underlying
  16142. * query.
  16143. */ data() {
  16144. return this._data;
  16145. }
  16146. }
  16147. /**
  16148. * @license
  16149. * Copyright 2022 Google LLC
  16150. *
  16151. * Licensed under the Apache License, Version 2.0 (the "License");
  16152. * you may not use this file except in compliance with the License.
  16153. * You may obtain a copy of the License at
  16154. *
  16155. * http://www.apache.org/licenses/LICENSE-2.0
  16156. *
  16157. * Unless required by applicable law or agreed to in writing, software
  16158. * distributed under the License is distributed on an "AS IS" BASIS,
  16159. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16160. * See the License for the specific language governing permissions and
  16161. * limitations under the License.
  16162. */
  16163. /**
  16164. * CountQueryRunner encapsulates the logic needed to run the count aggregation
  16165. * queries.
  16166. */ class Ca {
  16167. constructor(t, e, n) {
  16168. this.query = t, this.datastore = e, this.userDataWriter = n;
  16169. }
  16170. run() {
  16171. return bu(this.datastore, this.query._query).then((t => {
  16172. M(void 0 !== t[0]);
  16173. const e = Object.entries(t[0]).filter((([t, e]) => "count_alias" === t)).map((([t, e]) => this.userDataWriter.convertValue(e)))[0];
  16174. return M("number" == typeof e), Promise.resolve(new Da(this.query, {
  16175. count: e
  16176. }));
  16177. }));
  16178. }
  16179. }
  16180. /**
  16181. * @license
  16182. * Copyright 2017 Google LLC
  16183. *
  16184. * Licensed under the Apache License, Version 2.0 (the "License");
  16185. * you may not use this file except in compliance with the License.
  16186. * You may obtain a copy of the License at
  16187. *
  16188. * http://www.apache.org/licenses/LICENSE-2.0
  16189. *
  16190. * Unless required by applicable law or agreed to in writing, software
  16191. * distributed under the License is distributed on an "AS IS" BASIS,
  16192. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16193. * See the License for the specific language governing permissions and
  16194. * limitations under the License.
  16195. */
  16196. /**
  16197. * Internal transaction object responsible for accumulating the mutations to
  16198. * perform and the base versions for any documents read.
  16199. */ class xa {
  16200. constructor(t) {
  16201. this.datastore = t,
  16202. // The version of each document that was read during this transaction.
  16203. this.readVersions = new Map, this.mutations = [], this.committed = !1,
  16204. /**
  16205. * A deferred usage error that occurred previously in this transaction that
  16206. * will cause the transaction to fail once it actually commits.
  16207. */
  16208. this.lastWriteError = null,
  16209. /**
  16210. * Set of documents that have been written in the transaction.
  16211. *
  16212. * When there's more than one write to the same key in a transaction, any
  16213. * writes after the first are handled differently.
  16214. */
  16215. this.writtenDocs = new Set;
  16216. }
  16217. async lookup(t) {
  16218. if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new L(B.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes.");
  16219. const e = await async function(t, e) {
  16220. const n = $(t), s = zs(n.yt) + "/documents", i = {
  16221. documents: e.map((t => Gs(n.yt, t)))
  16222. }, r = await n._o("BatchGetDocuments", s, i, e.length), o = new Map;
  16223. r.forEach((t => {
  16224. const e = Xs(n.yt, t);
  16225. o.set(e.key.toString(), e);
  16226. }));
  16227. const u = [];
  16228. return e.forEach((t => {
  16229. const e = o.get(t.toString());
  16230. M(!!e), u.push(e);
  16231. })), u;
  16232. }(this.datastore, t);
  16233. return e.forEach((t => this.recordVersion(t))), e;
  16234. }
  16235. set(t, e) {
  16236. this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  16237. }
  16238. update(t, e) {
  16239. try {
  16240. this.write(e.toMutation(t, this.preconditionForUpdate(t)));
  16241. } catch (t) {
  16242. this.lastWriteError = t;
  16243. }
  16244. this.writtenDocs.add(t.toString());
  16245. }
  16246. delete(t) {
  16247. this.write(new is(t, this.precondition(t))), this.writtenDocs.add(t.toString());
  16248. }
  16249. async commit() {
  16250. if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError;
  16251. const t = this.readVersions;
  16252. // For each mutation, note that the doc was written.
  16253. this.mutations.forEach((e => {
  16254. t.delete(e.key.toString());
  16255. })),
  16256. // For each document that was read but not written to, we want to perform
  16257. // a `verify` operation.
  16258. t.forEach(((t, e) => {
  16259. const n = ct.fromPath(e);
  16260. this.mutations.push(new rs(n, this.precondition(n)));
  16261. })), await async function(t, e) {
  16262. const n = $(t), s = zs(n.yt) + "/documents", i = {
  16263. writes: e.map((t => ti(n.yt, t)))
  16264. };
  16265. await n.ao("Commit", s, i);
  16266. }(this.datastore, this.mutations), this.committed = !0;
  16267. }
  16268. recordVersion(t) {
  16269. let e;
  16270. if (t.isFoundDocument()) e = t.version; else {
  16271. if (!t.isNoDocument()) throw O();
  16272. // Represent a deleted doc using SnapshotVersion.min().
  16273. e = st.min();
  16274. }
  16275. const n = this.readVersions.get(t.key.toString());
  16276. if (n) {
  16277. if (!e.isEqual(n))
  16278. // This transaction will fail no matter what.
  16279. throw new L(B.ABORTED, "Document version changed between two reads.");
  16280. } else this.readVersions.set(t.key.toString(), e);
  16281. }
  16282. /**
  16283. * Returns the version of this document when it was read in this transaction,
  16284. * as a precondition, or no precondition if it was not read.
  16285. */ precondition(t) {
  16286. const e = this.readVersions.get(t.toString());
  16287. return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(st.min()) ? Qn.exists(!1) : Qn.updateTime(e) : Qn.none();
  16288. }
  16289. /**
  16290. * Returns the precondition for a document if the operation is an update.
  16291. */ preconditionForUpdate(t) {
  16292. const e = this.readVersions.get(t.toString());
  16293. // The first time a document is written, we want to take into account the
  16294. // read time and existence
  16295. if (!this.writtenDocs.has(t.toString()) && e) {
  16296. if (e.isEqual(st.min()))
  16297. // The document doesn't exist, so fail the transaction.
  16298. // This has to be validated locally because you can't send a
  16299. // precondition that a document does not exist without changing the
  16300. // semantics of the backend write to be an insert. This is the reverse
  16301. // of what we want, since we want to assert that the document doesn't
  16302. // exist but then send the update and have it fail. Since we can't
  16303. // express that to the backend, we have to validate locally.
  16304. // Note: this can change once we can send separate verify writes in the
  16305. // transaction.
  16306. throw new L(B.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
  16307. // Document exists, base precondition on document update time.
  16308. return Qn.updateTime(e);
  16309. }
  16310. // Document was not read, so we just use the preconditions for a blind
  16311. // update.
  16312. return Qn.exists(!0);
  16313. }
  16314. write(t) {
  16315. this.ensureCommitNotCalled(), this.mutations.push(t);
  16316. }
  16317. ensureCommitNotCalled() {}
  16318. }
  16319. /**
  16320. * @license
  16321. * Copyright 2019 Google LLC
  16322. *
  16323. * Licensed under the Apache License, Version 2.0 (the "License");
  16324. * you may not use this file except in compliance with the License.
  16325. * You may obtain a copy of the License at
  16326. *
  16327. * http://www.apache.org/licenses/LICENSE-2.0
  16328. *
  16329. * Unless required by applicable law or agreed to in writing, software
  16330. * distributed under the License is distributed on an "AS IS" BASIS,
  16331. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16332. * See the License for the specific language governing permissions and
  16333. * limitations under the License.
  16334. */
  16335. /**
  16336. * TransactionRunner encapsulates the logic needed to run and retry transactions
  16337. * with backoff.
  16338. */ class Na {
  16339. constructor(t, e, n, s, i) {
  16340. this.asyncQueue = t, this.datastore = e, this.options = n, this.updateFunction = s,
  16341. this.deferred = i, this.kc = n.maxAttempts, this.xo = new Iu(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */);
  16342. }
  16343. /** Runs the transaction and sets the result on deferred. */ run() {
  16344. this.kc -= 1, this.Oc();
  16345. }
  16346. Oc() {
  16347. this.xo.Ro((async () => {
  16348. const t = new xa(this.datastore), e = this.Mc(t);
  16349. e && e.then((e => {
  16350. this.asyncQueue.enqueueAndForget((() => t.commit().then((() => {
  16351. this.deferred.resolve(e);
  16352. })).catch((t => {
  16353. this.Fc(t);
  16354. }))));
  16355. })).catch((t => {
  16356. this.Fc(t);
  16357. }));
  16358. }));
  16359. }
  16360. Mc(t) {
  16361. try {
  16362. const e = this.updateFunction(t);
  16363. return !qt(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")),
  16364. null);
  16365. } catch (t) {
  16366. // Do not retry errors thrown by user provided updateFunction.
  16367. return this.deferred.reject(t), null;
  16368. }
  16369. }
  16370. Fc(t) {
  16371. this.kc > 0 && this.$c(t) ? (this.kc -= 1, this.asyncQueue.enqueueAndForget((() => (this.Oc(),
  16372. Promise.resolve())))) : this.deferred.reject(t);
  16373. }
  16374. $c(t) {
  16375. if ("FirebaseError" === t.name) {
  16376. // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and
  16377. // non-matching document versions with ABORTED. These errors should be retried.
  16378. const e = t.code;
  16379. return "aborted" === e || "failed-precondition" === e || "already-exists" === e || !as(e);
  16380. }
  16381. return !1;
  16382. }
  16383. }
  16384. /**
  16385. * @license
  16386. * Copyright 2017 Google LLC
  16387. *
  16388. * Licensed under the Apache License, Version 2.0 (the "License");
  16389. * you may not use this file except in compliance with the License.
  16390. * You may obtain a copy of the License at
  16391. *
  16392. * http://www.apache.org/licenses/LICENSE-2.0
  16393. *
  16394. * Unless required by applicable law or agreed to in writing, software
  16395. * distributed under the License is distributed on an "AS IS" BASIS,
  16396. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16397. * See the License for the specific language governing permissions and
  16398. * limitations under the License.
  16399. */
  16400. /**
  16401. * FirestoreClient is a top-level class that constructs and owns all of the
  16402. * pieces of the client SDK architecture. It is responsible for creating the
  16403. * async queue that is shared by all of the other components in the system.
  16404. */
  16405. class ka {
  16406. constructor(t, e,
  16407. /**
  16408. * Asynchronous queue responsible for all of our internal processing. When
  16409. * we get incoming work from the user (via public API) or the network
  16410. * (incoming GRPC messages), we should always schedule onto this queue.
  16411. * This ensures all of our work is properly serialized (e.g. we don't
  16412. * start processing a new operation while the previous one is waiting for
  16413. * an async I/O to complete).
  16414. */
  16415. n, s) {
  16416. this.authCredentials = t, this.appCheckCredentials = e, this.asyncQueue = n, this.databaseInfo = s,
  16417. this.user = P.UNAUTHENTICATED, this.clientId = X.R(), this.authCredentialListener = () => Promise.resolve(),
  16418. this.appCheckCredentialListener = () => Promise.resolve(), this.authCredentials.start(n, (async t => {
  16419. C("FirestoreClient", "Received user=", t.uid), await this.authCredentialListener(t),
  16420. this.user = t;
  16421. })), this.appCheckCredentials.start(n, (t => (C("FirestoreClient", "Received new app check token=", t),
  16422. this.appCheckCredentialListener(t, this.user))));
  16423. }
  16424. async getConfiguration() {
  16425. return {
  16426. asyncQueue: this.asyncQueue,
  16427. databaseInfo: this.databaseInfo,
  16428. clientId: this.clientId,
  16429. authCredentials: this.authCredentials,
  16430. appCheckCredentials: this.appCheckCredentials,
  16431. initialUser: this.user,
  16432. maxConcurrentLimboResolutions: 100
  16433. };
  16434. }
  16435. setCredentialChangeListener(t) {
  16436. this.authCredentialListener = t;
  16437. }
  16438. setAppCheckTokenChangeListener(t) {
  16439. this.appCheckCredentialListener = t;
  16440. }
  16441. /**
  16442. * Checks that the client has not been terminated. Ensures that other methods on
  16443. * this class cannot be called after the client is terminated.
  16444. */ verifyNotTerminated() {
  16445. if (this.asyncQueue.isShuttingDown) throw new L(B.FAILED_PRECONDITION, "The client has already been terminated.");
  16446. }
  16447. terminate() {
  16448. this.asyncQueue.enterRestrictedMode();
  16449. const t = new q;
  16450. return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => {
  16451. try {
  16452. this.onlineComponents && await this.onlineComponents.terminate(), this.offlineComponents && await this.offlineComponents.terminate(),
  16453. // The credentials provider must be terminated after shutting down the
  16454. // RemoteStore as it will prevent the RemoteStore from retrieving auth
  16455. // tokens.
  16456. this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), t.resolve();
  16457. } catch (e) {
  16458. const n = sc(e, "Failed to shutdown persistence");
  16459. t.reject(n);
  16460. }
  16461. })), t.promise;
  16462. }
  16463. }
  16464. async function Oa(t, e) {
  16465. t.asyncQueue.verifyOperationInProgress(), C("FirestoreClient", "Initializing OfflineComponentProvider");
  16466. const n = await t.getConfiguration();
  16467. await e.initialize(n);
  16468. let s = n.initialUser;
  16469. t.setCredentialChangeListener((async t => {
  16470. s.isEqual(t) || (await Uo(e.localStore, t), s = t);
  16471. })),
  16472. // When a user calls clearPersistence() in one client, all other clients
  16473. // need to be terminated to allow the delete to succeed.
  16474. e.persistence.setDatabaseDeletedListener((() => t.terminate())), t.offlineComponents = e;
  16475. }
  16476. async function Ma(t, e) {
  16477. t.asyncQueue.verifyOperationInProgress();
  16478. const n = await Fa(t);
  16479. C("FirestoreClient", "Initializing OnlineComponentProvider");
  16480. const s = await t.getConfiguration();
  16481. await e.initialize(n, s),
  16482. // The CredentialChangeListener of the online component provider takes
  16483. // precedence over the offline component provider.
  16484. t.setCredentialChangeListener((t => Xu(e.remoteStore, t))), t.setAppCheckTokenChangeListener(((t, n) => Xu(e.remoteStore, n))),
  16485. t.onlineComponents = e;
  16486. }
  16487. async function Fa(t) {
  16488. return t.offlineComponents || (C("FirestoreClient", "Using default OfflineComponentProvider"),
  16489. await Oa(t, new sa)), t.offlineComponents;
  16490. }
  16491. async function $a(t) {
  16492. return t.onlineComponents || (C("FirestoreClient", "Using default OnlineComponentProvider"),
  16493. await Ma(t, new oa)), t.onlineComponents;
  16494. }
  16495. function Ba(t) {
  16496. return Fa(t).then((t => t.persistence));
  16497. }
  16498. function La(t) {
  16499. return Fa(t).then((t => t.localStore));
  16500. }
  16501. function qa(t) {
  16502. return $a(t).then((t => t.remoteStore));
  16503. }
  16504. function Ua(t) {
  16505. return $a(t).then((t => t.syncEngine));
  16506. }
  16507. function Ka(t) {
  16508. return $a(t).then((t => t.datastore));
  16509. }
  16510. async function Ga(t) {
  16511. const e = await $a(t), n = e.eventManager;
  16512. return n.onListen = bc.bind(null, e.syncEngine), n.onUnlisten = vc.bind(null, e.syncEngine),
  16513. n;
  16514. }
  16515. /** Enables the network connection and re-enqueues all pending operations. */ function Qa(t) {
  16516. return t.asyncQueue.enqueue((async () => {
  16517. const e = await Ba(t), n = await qa(t);
  16518. return e.setNetworkEnabled(!0), function(t) {
  16519. const e = $(t);
  16520. return e._u.delete(0 /* OfflineCause.UserDisabled */), Vu(e);
  16521. }(n);
  16522. }));
  16523. }
  16524. /** Disables the network connection. Pending operations will not complete. */ function ja(t) {
  16525. return t.asyncQueue.enqueue((async () => {
  16526. const e = await Ba(t), n = await qa(t);
  16527. return e.setNetworkEnabled(!1), async function(t) {
  16528. const e = $(t);
  16529. e._u.add(0 /* OfflineCause.UserDisabled */), await Su(e),
  16530. // Set the OnlineState to Offline so get()s return from cache, etc.
  16531. e.gu.set("Offline" /* OnlineState.Offline */);
  16532. }(n);
  16533. }));
  16534. }
  16535. /**
  16536. * Returns a Promise that resolves when all writes that were pending at the time
  16537. * this method was called received server acknowledgement. An acknowledgement
  16538. * can be either acceptance or rejection.
  16539. */ function Wa(t, e) {
  16540. const n = new q;
  16541. return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {
  16542. try {
  16543. const s = await function(t, e) {
  16544. const n = $(t);
  16545. return n.persistence.runTransaction("read document", "readonly", (t => n.localDocuments.getDocument(t, e)));
  16546. }(t, e);
  16547. s.isFoundDocument() ? n.resolve(s) : s.isNoDocument() ? n.resolve(null) : n.reject(new L(B.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.)"));
  16548. } catch (t) {
  16549. const s = sc(t, `Failed to get document '${e} from cache`);
  16550. n.reject(s);
  16551. }
  16552. }
  16553. /**
  16554. * Retrieves a latency-compensated document from the backend via a
  16555. * SnapshotListener.
  16556. */ (await La(t), e, n))), n.promise;
  16557. }
  16558. function za(t, e, n = {}) {
  16559. const s = new q;
  16560. return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {
  16561. const r = new va({
  16562. next: r => {
  16563. // Remove query first before passing event to user to avoid
  16564. // user actions affecting the now stale query.
  16565. e.enqueueAndForget((() => hc(t, o)));
  16566. const u = r.docs.has(n);
  16567. !u && r.fromCache ?
  16568. // TODO(dimond): If we're online and the document doesn't
  16569. // exist then we resolve with a doc.exists set to false. If
  16570. // we're offline however, we reject the Promise in this
  16571. // case. Two options: 1) Cache the negative response from
  16572. // the server so we can deliver that even when you're
  16573. // offline 2) Actually reject the Promise in the online case
  16574. // if the document doesn't exist.
  16575. i.reject(new L(B.UNAVAILABLE, "Failed to get document because the client is offline.")) : u && r.fromCache && s && "server" === s.source ? i.reject(new L(B.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')) : i.resolve(r);
  16576. },
  16577. error: t => i.reject(t)
  16578. }), o = new _c(ln(n.path), r, {
  16579. includeMetadataChanges: !0,
  16580. Nu: !0
  16581. });
  16582. return ac(t, o);
  16583. }(await Ga(t), t.asyncQueue, e, n, s))), s.promise;
  16584. }
  16585. function Ha(t, e) {
  16586. const n = new q;
  16587. return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {
  16588. try {
  16589. const s = await Jo(t, e,
  16590. /* usePreviousResults= */ !0), i = new Tc(e, s.Hi), r = i.Wu(s.documents), o = i.applyChanges(r,
  16591. /* updateLimboDocuments= */ !1);
  16592. n.resolve(o.snapshot);
  16593. } catch (t) {
  16594. const s = sc(t, `Failed to execute query '${e} against cache`);
  16595. n.reject(s);
  16596. }
  16597. }
  16598. /**
  16599. * Retrieves a latency-compensated query snapshot from the backend via a
  16600. * SnapshotListener.
  16601. */ (await La(t), e, n))), n.promise;
  16602. }
  16603. function Ja(t, e, n = {}) {
  16604. const s = new q;
  16605. return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {
  16606. const r = new va({
  16607. next: n => {
  16608. // Remove query first before passing event to user to avoid
  16609. // user actions affecting the now stale query.
  16610. e.enqueueAndForget((() => hc(t, o))), n.fromCache && "server" === s.source ? i.reject(new L(B.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);
  16611. },
  16612. error: t => i.reject(t)
  16613. }), o = new _c(n, r, {
  16614. includeMetadataChanges: !0,
  16615. Nu: !0
  16616. });
  16617. return ac(t, o);
  16618. }(await Ga(t), t.asyncQueue, e, n, s))), s.promise;
  16619. }
  16620. function Ya(t, e) {
  16621. const n = new va(e);
  16622. return t.asyncQueue.enqueueAndForget((async () => function(t, e) {
  16623. $(t).Ru.add(e),
  16624. // Immediately fire an initial event, indicating all existing listeners
  16625. // are in-sync.
  16626. e.next();
  16627. }(await Ga(t), n))), () => {
  16628. n.bc(), t.asyncQueue.enqueueAndForget((async () => function(t, e) {
  16629. $(t).Ru.delete(e);
  16630. }(await Ga(t), n)));
  16631. };
  16632. }
  16633. /**
  16634. * Takes an updateFunction in which a set of reads and writes can be performed
  16635. * atomically. In the updateFunction, the client can read and write values
  16636. * using the supplied transaction object. After the updateFunction, all
  16637. * changes will be committed. If a retryable error occurs (ex: some other
  16638. * client has changed any of the data referenced), then the updateFunction
  16639. * will be called again after a backoff. If the updateFunction still fails
  16640. * after all retries, then the transaction will be rejected.
  16641. *
  16642. * The transaction object passed to the updateFunction contains methods for
  16643. * accessing documents and collections. Unlike other datastore access, data
  16644. * accessed with the transaction will not reflect local changes that have not
  16645. * been committed. For this reason, it is required that all reads are
  16646. * performed before any writes. Transactions must be performed while online.
  16647. */ function Xa(t, e, n, s) {
  16648. const i = function(t, e) {
  16649. let n;
  16650. n = "string" == typeof t ? (new TextEncoder).encode(t) : t;
  16651. return function(t, e) {
  16652. return new Va(t, e);
  16653. }(function(t, e) {
  16654. if (t instanceof Uint8Array) return Pa(t, e);
  16655. if (t instanceof ArrayBuffer) return Pa(new Uint8Array(t), e);
  16656. if (t instanceof ReadableStream) return t.getReader();
  16657. throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream");
  16658. }(n), e);
  16659. }
  16660. /**
  16661. * @license
  16662. * Copyright 2020 Google LLC
  16663. *
  16664. * Licensed under the Apache License, Version 2.0 (the "License");
  16665. * you may not use this file except in compliance with the License.
  16666. * You may obtain a copy of the License at
  16667. *
  16668. * http://www.apache.org/licenses/LICENSE-2.0
  16669. *
  16670. * Unless required by applicable law or agreed to in writing, software
  16671. * distributed under the License is distributed on an "AS IS" BASIS,
  16672. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16673. * See the License for the specific language governing permissions and
  16674. * limitations under the License.
  16675. */ (n, pu(e));
  16676. t.asyncQueue.enqueueAndForget((async () => {
  16677. na(await Ua(t), i, s);
  16678. }));
  16679. }
  16680. function Za(t, e) {
  16681. return t.asyncQueue.enqueue((async () => function(t, e) {
  16682. const n = $(t);
  16683. return n.persistence.runTransaction("Get named query", "readonly", (t => n.Ns.getNamedQuery(t, e)));
  16684. }(await La(t), e)));
  16685. }
  16686. class th {
  16687. constructor() {
  16688. // The last promise in the queue.
  16689. this.Bc = Promise.resolve(),
  16690. // A list of retryable operations. Retryable operations are run in order and
  16691. // retried with backoff.
  16692. this.Lc = [],
  16693. // Is this AsyncQueue being shut down? Once it is set to true, it will not
  16694. // be changed again.
  16695. this.qc = !1,
  16696. // Operations scheduled to be queued in the future. Operations are
  16697. // automatically removed after they are run or canceled.
  16698. this.Uc = [],
  16699. // visible for testing
  16700. this.Kc = null,
  16701. // Flag set while there's an outstanding AsyncQueue operation, used for
  16702. // assertion sanity-checks.
  16703. this.Gc = !1,
  16704. // Enabled during shutdown on Safari to prevent future access to IndexedDB.
  16705. this.Qc = !1,
  16706. // List of TimerIds to fast-forward delays for.
  16707. this.jc = [],
  16708. // Backoff timer used to schedule retries for retryable operations
  16709. this.xo = new Iu(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */),
  16710. // Visibility handler that triggers an immediate retry of all retryable
  16711. // operations. Meant to speed up recovery when we regain file system access
  16712. // after page comes into foreground.
  16713. this.Wc = () => {
  16714. const t = yu();
  16715. t && C("AsyncQueue", "Visibility state changed to " + t.visibilityState), this.xo.Po();
  16716. };
  16717. const t = yu();
  16718. t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this.Wc);
  16719. }
  16720. get isShuttingDown() {
  16721. return this.qc;
  16722. }
  16723. /**
  16724. * Adds a new operation to the queue without waiting for it to complete (i.e.
  16725. * we ignore the Promise result).
  16726. */ enqueueAndForget(t) {
  16727. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  16728. this.enqueue(t);
  16729. }
  16730. enqueueAndForgetEvenWhileRestricted(t) {
  16731. this.zc(),
  16732. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  16733. this.Hc(t);
  16734. }
  16735. enterRestrictedMode(t) {
  16736. if (!this.qc) {
  16737. this.qc = !0, this.Qc = t || !1;
  16738. const e = yu();
  16739. e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Wc);
  16740. }
  16741. }
  16742. enqueue(t) {
  16743. if (this.zc(), this.qc)
  16744. // Return a Promise which never resolves.
  16745. return new Promise((() => {}));
  16746. // Create a deferred Promise that we can return to the callee. This
  16747. // allows us to return a "hanging Promise" only to the callee and still
  16748. // advance the queue even when the operation is not run.
  16749. const e = new q;
  16750. return this.Hc((() => this.qc && this.Qc ? Promise.resolve() : (t().then(e.resolve, e.reject),
  16751. e.promise))).then((() => e.promise));
  16752. }
  16753. enqueueRetryable(t) {
  16754. this.enqueueAndForget((() => (this.Lc.push(t), this.Jc())));
  16755. }
  16756. /**
  16757. * Runs the next operation from the retryable queue. If the operation fails,
  16758. * reschedules with backoff.
  16759. */ async Jc() {
  16760. if (0 !== this.Lc.length) {
  16761. try {
  16762. await this.Lc[0](), this.Lc.shift(), this.xo.reset();
  16763. } catch (t) {
  16764. if (!Vt(t)) throw t;
  16765. // Failure will be handled by AsyncQueue
  16766. C("AsyncQueue", "Operation failed with retryable error: " + t);
  16767. }
  16768. this.Lc.length > 0 &&
  16769. // If there are additional operations, we re-schedule `retryNextOp()`.
  16770. // This is necessary to run retryable operations that failed during
  16771. // their initial attempt since we don't know whether they are already
  16772. // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
  16773. // needs to be re-run, we will run `op1`, `op1`, `op2` using the
  16774. // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
  16775. // call scheduled here.
  16776. // Since `backoffAndRun()` cancels an existing backoff and schedules a
  16777. // new backoff on every call, there is only ever a single additional
  16778. // operation in the queue.
  16779. this.xo.Ro((() => this.Jc()));
  16780. }
  16781. }
  16782. Hc(t) {
  16783. const e = this.Bc.then((() => (this.Gc = !0, t().catch((t => {
  16784. this.Kc = t, this.Gc = !1;
  16785. const e =
  16786. /**
  16787. * Chrome includes Error.message in Error.stack. Other browsers do not.
  16788. * This returns expected output of message + stack when available.
  16789. * @param error - Error or FirestoreError
  16790. */
  16791. function(t) {
  16792. let e = t.message || "";
  16793. t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack);
  16794. return e;
  16795. }
  16796. /**
  16797. * @license
  16798. * Copyright 2017 Google LLC
  16799. *
  16800. * Licensed under the Apache License, Version 2.0 (the "License");
  16801. * you may not use this file except in compliance with the License.
  16802. * You may obtain a copy of the License at
  16803. *
  16804. * http://www.apache.org/licenses/LICENSE-2.0
  16805. *
  16806. * Unless required by applicable law or agreed to in writing, software
  16807. * distributed under the License is distributed on an "AS IS" BASIS,
  16808. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16809. * See the License for the specific language governing permissions and
  16810. * limitations under the License.
  16811. */ (t);
  16812. // Re-throw the error so that this.tail becomes a rejected Promise and
  16813. // all further attempts to chain (via .then) will just short-circuit
  16814. // and return the rejected Promise.
  16815. throw x("INTERNAL UNHANDLED ERROR: ", e), t;
  16816. })).then((t => (this.Gc = !1, t))))));
  16817. return this.Bc = e, e;
  16818. }
  16819. enqueueAfterDelay(t, e, n) {
  16820. this.zc(),
  16821. // Fast-forward delays for timerIds that have been overriden.
  16822. this.jc.indexOf(t) > -1 && (e = 0);
  16823. const s = nc.createAndSchedule(this, t, e, n, (t => this.Yc(t)));
  16824. return this.Uc.push(s), s;
  16825. }
  16826. zc() {
  16827. this.Kc && O();
  16828. }
  16829. verifyOperationInProgress() {}
  16830. /**
  16831. * Waits until all currently queued tasks are finished executing. Delayed
  16832. * operations are not run.
  16833. */ async Xc() {
  16834. // Operations in the queue prior to draining may have enqueued additional
  16835. // operations. Keep draining the queue until the tail is no longer advanced,
  16836. // which indicates that no more new operations were enqueued and that all
  16837. // operations were executed.
  16838. let t;
  16839. do {
  16840. t = this.Bc, await t;
  16841. } while (t !== this.Bc);
  16842. }
  16843. /**
  16844. * For Tests: Determine if a delayed operation with a particular TimerId
  16845. * exists.
  16846. */ Zc(t) {
  16847. for (const e of this.Uc) if (e.timerId === t) return !0;
  16848. return !1;
  16849. }
  16850. /**
  16851. * For Tests: Runs some or all delayed operations early.
  16852. *
  16853. * @param lastTimerId - Delayed operations up to and including this TimerId
  16854. * will be drained. Pass TimerId.All to run all delayed operations.
  16855. * @returns a Promise that resolves once all operations have been run.
  16856. */ ta(t) {
  16857. // Note that draining may generate more delayed ops, so we do that first.
  16858. return this.Xc().then((() => {
  16859. // Run ops in the same order they'd run if they ran naturally.
  16860. this.Uc.sort(((t, e) => t.targetTimeMs - e.targetTimeMs));
  16861. for (const e of this.Uc) if (e.skipDelay(), "all" /* TimerId.All */ !== t && e.timerId === t) break;
  16862. return this.Xc();
  16863. }));
  16864. }
  16865. /**
  16866. * For Tests: Skip all subsequent delays for a timer id.
  16867. */ ea(t) {
  16868. this.jc.push(t);
  16869. }
  16870. /** Called once a DelayedOperation is run or canceled. */ Yc(t) {
  16871. // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
  16872. const e = this.Uc.indexOf(t);
  16873. this.Uc.splice(e, 1);
  16874. }
  16875. }
  16876. function eh(t) {
  16877. /**
  16878. * Returns true if obj is an object and contains at least one of the specified
  16879. * methods.
  16880. */
  16881. return function(t, e) {
  16882. if ("object" != typeof t || null === t) return !1;
  16883. const n = t;
  16884. for (const t of e) if (t in n && "function" == typeof n[t]) return !0;
  16885. return !1;
  16886. }
  16887. /**
  16888. * @license
  16889. * Copyright 2020 Google LLC
  16890. *
  16891. * Licensed under the Apache License, Version 2.0 (the "License");
  16892. * you may not use this file except in compliance with the License.
  16893. * You may obtain a copy of the License at
  16894. *
  16895. * http://www.apache.org/licenses/LICENSE-2.0
  16896. *
  16897. * Unless required by applicable law or agreed to in writing, software
  16898. * distributed under the License is distributed on an "AS IS" BASIS,
  16899. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16900. * See the License for the specific language governing permissions and
  16901. * limitations under the License.
  16902. */
  16903. /**
  16904. * Represents the task of loading a Firestore bundle. It provides progress of bundle
  16905. * loading, as well as task completion and error events.
  16906. *
  16907. * The API is compatible with `Promise<LoadBundleTaskProgress>`.
  16908. */ (t, [ "next", "error", "complete" ]);
  16909. }
  16910. class nh {
  16911. constructor() {
  16912. this._progressObserver = {}, this._taskCompletionResolver = new q, this._lastProgress = {
  16913. taskState: "Running",
  16914. totalBytes: 0,
  16915. totalDocuments: 0,
  16916. bytesLoaded: 0,
  16917. documentsLoaded: 0
  16918. };
  16919. }
  16920. /**
  16921. * Registers functions to listen to bundle loading progress events.
  16922. * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur
  16923. * each time a Firestore document is loaded from the bundle.
  16924. * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the
  16925. * error, and there should be no more updates after this.
  16926. * @param complete - Called when the loading task is complete.
  16927. */ onProgress(t, e, n) {
  16928. this._progressObserver = {
  16929. next: t,
  16930. error: e,
  16931. complete: n
  16932. };
  16933. }
  16934. /**
  16935. * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.
  16936. *
  16937. * @param onRejected - Called when an error occurs during bundle loading.
  16938. */ catch(t) {
  16939. return this._taskCompletionResolver.promise.catch(t);
  16940. }
  16941. /**
  16942. * Implements the `Promise<LoadBundleTaskProgress>.then` interface.
  16943. *
  16944. * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.
  16945. * The update will always have its `taskState` set to `"Success"`.
  16946. * @param onRejected - Called when an error occurs during bundle loading.
  16947. */ then(t, e) {
  16948. return this._taskCompletionResolver.promise.then(t, e);
  16949. }
  16950. /**
  16951. * Notifies all observers that bundle loading has completed, with a provided
  16952. * `LoadBundleTaskProgress` object.
  16953. *
  16954. * @private
  16955. */ _completeWith(t) {
  16956. this._updateProgress(t), this._progressObserver.complete && this._progressObserver.complete(),
  16957. this._taskCompletionResolver.resolve(t);
  16958. }
  16959. /**
  16960. * Notifies all observers that bundle loading has failed, with a provided
  16961. * `Error` as the reason.
  16962. *
  16963. * @private
  16964. */ _failWith(t) {
  16965. this._lastProgress.taskState = "Error", this._progressObserver.next && this._progressObserver.next(this._lastProgress),
  16966. this._progressObserver.error && this._progressObserver.error(t), this._taskCompletionResolver.reject(t);
  16967. }
  16968. /**
  16969. * Notifies a progress update of loading a bundle.
  16970. * @param progress - The new progress.
  16971. *
  16972. * @private
  16973. */ _updateProgress(t) {
  16974. this._lastProgress = t, this._progressObserver.next && this._progressObserver.next(t);
  16975. }
  16976. }
  16977. /**
  16978. * @license
  16979. * Copyright 2020 Google LLC
  16980. *
  16981. * Licensed under the Apache License, Version 2.0 (the "License");
  16982. * you may not use this file except in compliance with the License.
  16983. * You may obtain a copy of the License at
  16984. *
  16985. * http://www.apache.org/licenses/LICENSE-2.0
  16986. *
  16987. * Unless required by applicable law or agreed to in writing, software
  16988. * distributed under the License is distributed on an "AS IS" BASIS,
  16989. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16990. * See the License for the specific language governing permissions and
  16991. * limitations under the License.
  16992. */
  16993. /** DOMException error code constants. */ const sh = -1;
  16994. /**
  16995. * The Cloud Firestore service interface.
  16996. *
  16997. * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
  16998. */
  16999. class ih extends ma {
  17000. /** @hideconstructor */
  17001. constructor(t, e, n, s) {
  17002. super(t, e, n, s),
  17003. /**
  17004. * Whether it's a {@link Firestore} or Firestore Lite instance.
  17005. */
  17006. this.type = "firestore", this._queue = new th, this._persistenceKey = (null == s ? void 0 : s.name) || "[DEFAULT]";
  17007. }
  17008. _terminate() {
  17009. return this._firestoreClient ||
  17010. // The client must be initialized to ensure that all subsequent API
  17011. // usage throws an exception.
  17012. ch(this), this._firestoreClient.terminate();
  17013. }
  17014. }
  17015. /**
  17016. * Initializes a new instance of {@link Firestore} with the provided settings.
  17017. * Can only be called before any other function, including
  17018. * {@link (getFirestore:1)}. If the custom settings are empty, this function is
  17019. * equivalent to calling {@link (getFirestore:1)}.
  17020. *
  17021. * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will
  17022. * be associated.
  17023. * @param settings - A settings object to configure the {@link Firestore} instance.
  17024. * @param databaseId - The name of database.
  17025. * @returns A newly initialized {@link Firestore} instance.
  17026. */ function rh(t, e, n) {
  17027. n || (n = "(default)");
  17028. const s = _getProvider(t, "firestore");
  17029. if (s.isInitialized(n)) {
  17030. const t = s.getImmediate({
  17031. identifier: n
  17032. }), i = s.getOptions(n);
  17033. if (deepEqual(i, e)) return t;
  17034. throw new L(B.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.");
  17035. }
  17036. if (void 0 !== e.cacheSizeBytes && -1 !== e.cacheSizeBytes && e.cacheSizeBytes < 1048576) throw new L(B.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
  17037. return s.initialize({
  17038. options: e,
  17039. instanceIdentifier: n
  17040. });
  17041. }
  17042. function oh(e, n) {
  17043. const s = "object" == typeof e ? e : getApp(), i = "string" == typeof e ? e : n || "(default)", r = _getProvider(s, "firestore").getImmediate({
  17044. identifier: i
  17045. });
  17046. if (!r._initialized) {
  17047. const t = getDefaultEmulatorHostnameAndPort("firestore");
  17048. t && ga(r, ...t);
  17049. }
  17050. return r;
  17051. }
  17052. /**
  17053. * @internal
  17054. */ function uh(t) {
  17055. return t._firestoreClient || ch(t), t._firestoreClient.verifyNotTerminated(), t._firestoreClient;
  17056. }
  17057. function ch(t) {
  17058. var e;
  17059. const n = t._freezeSettings(), s = function(t, e, n, s) {
  17060. return new Mt(t, e, n, s.host, s.ssl, s.experimentalForceLongPolling, s.experimentalAutoDetectLongPolling, s.useFetchStreams);
  17061. }
  17062. /**
  17063. * @license
  17064. * Copyright 2020 Google LLC
  17065. *
  17066. * Licensed under the Apache License, Version 2.0 (the "License");
  17067. * you may not use this file except in compliance with the License.
  17068. * You may obtain a copy of the License at
  17069. *
  17070. * http://www.apache.org/licenses/LICENSE-2.0
  17071. *
  17072. * Unless required by applicable law or agreed to in writing, software
  17073. * distributed under the License is distributed on an "AS IS" BASIS,
  17074. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17075. * See the License for the specific language governing permissions and
  17076. * limitations under the License.
  17077. */
  17078. // settings() defaults:
  17079. (t._databaseId, (null === (e = t._app) || void 0 === e ? void 0 : e.options.appId) || "", t._persistenceKey, n);
  17080. t._firestoreClient = new ka(t._authCredentials, t._appCheckCredentials, t._queue, s);
  17081. }
  17082. /**
  17083. * Attempts to enable persistent storage, if possible.
  17084. *
  17085. * Must be called before any other functions (other than
  17086. * {@link initializeFirestore}, {@link (getFirestore:1)} or
  17087. * {@link clearIndexedDbPersistence}.
  17088. *
  17089. * If this fails, `enableIndexedDbPersistence()` will reject the promise it
  17090. * returns. Note that even after this failure, the {@link Firestore} instance will
  17091. * remain usable, however offline persistence will be disabled.
  17092. *
  17093. * There are several reasons why this can fail, which can be identified by
  17094. * the `code` on the error.
  17095. *
  17096. * * failed-precondition: The app is already open in another browser tab.
  17097. * * unimplemented: The browser is incompatible with the offline
  17098. * persistence implementation.
  17099. *
  17100. * @param firestore - The {@link Firestore} instance to enable persistence for.
  17101. * @param persistenceSettings - Optional settings object to configure
  17102. * persistence.
  17103. * @returns A `Promise` that represents successfully enabling persistent storage.
  17104. */ function ah(t, e) {
  17105. ph(t = fa(t, ih));
  17106. const n = uh(t), s = t._freezeSettings(), i = new oa;
  17107. return lh(n, i, new ia(i, s.cacheSizeBytes, null == e ? void 0 : e.forceOwnership));
  17108. }
  17109. /**
  17110. * Attempts to enable multi-tab persistent storage, if possible. If enabled
  17111. * across all tabs, all operations share access to local persistence, including
  17112. * shared execution of queries and latency-compensated local document updates
  17113. * across all connected instances.
  17114. *
  17115. * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise
  17116. * it returns. Note that even after this failure, the {@link Firestore} instance will
  17117. * remain usable, however offline persistence will be disabled.
  17118. *
  17119. * There are several reasons why this can fail, which can be identified by
  17120. * the `code` on the error.
  17121. *
  17122. * * failed-precondition: The app is already open in another browser tab and
  17123. * multi-tab is not enabled.
  17124. * * unimplemented: The browser is incompatible with the offline
  17125. * persistence implementation.
  17126. *
  17127. * @param firestore - The {@link Firestore} instance to enable persistence for.
  17128. * @returns A `Promise` that represents successfully enabling persistent
  17129. * storage.
  17130. */ function hh(t) {
  17131. ph(t = fa(t, ih));
  17132. const e = uh(t), n = t._freezeSettings(), s = new oa;
  17133. return lh(e, s, new ra(s, n.cacheSizeBytes));
  17134. }
  17135. /**
  17136. * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.
  17137. * If the operation fails with a recoverable error (see
  17138. * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected
  17139. * but the client remains usable.
  17140. */ function lh(t, e, n) {
  17141. const s = new q;
  17142. return t.asyncQueue.enqueue((async () => {
  17143. try {
  17144. await Oa(t, n), await Ma(t, e), s.resolve();
  17145. } catch (t) {
  17146. const e = t;
  17147. if (!
  17148. /**
  17149. * Decides whether the provided error allows us to gracefully disable
  17150. * persistence (as opposed to crashing the client).
  17151. */
  17152. function(t) {
  17153. if ("FirebaseError" === t.name) return t.code === B.FAILED_PRECONDITION || t.code === B.UNIMPLEMENTED;
  17154. if ("undefined" != typeof DOMException && t instanceof DOMException)
  17155. // There are a few known circumstances where we can open IndexedDb but
  17156. // trying to read/write will fail (e.g. quota exceeded). For
  17157. // well-understood cases, we attempt to detect these and then gracefully
  17158. // fall back to memory persistence.
  17159. // NOTE: Rather than continue to add to this list, we could decide to
  17160. // always fall back, with the risk that we might accidentally hide errors
  17161. // representing actual SDK bugs.
  17162. // When the browser is out of quota we could get either quota exceeded
  17163. // or an aborted error depending on whether the error happened during
  17164. // schema migration.
  17165. return 22 === t.code || 20 === t.code ||
  17166. // Firefox Private Browsing mode disables IndexedDb and returns
  17167. // INVALID_STATE for any usage.
  17168. 11 === t.code;
  17169. return !0;
  17170. }
  17171. /**
  17172. * Clears the persistent storage. This includes pending writes and cached
  17173. * documents.
  17174. *
  17175. * Must be called while the {@link Firestore} instance is not started (after the app is
  17176. * terminated or when the app is first initialized). On startup, this function
  17177. * must be called before other functions (other than {@link
  17178. * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}
  17179. * instance is still running, the promise will be rejected with the error code
  17180. * of `failed-precondition`.
  17181. *
  17182. * Note: `clearIndexedDbPersistence()` is primarily intended to help write
  17183. * reliable tests that use Cloud Firestore. It uses an efficient mechanism for
  17184. * dropping existing data but does not attempt to securely overwrite or
  17185. * otherwise make cached data unrecoverable. For applications that are sensitive
  17186. * to the disclosure of cached data in between user sessions, we strongly
  17187. * recommend not enabling persistence at all.
  17188. *
  17189. * @param firestore - The {@link Firestore} instance to clear persistence for.
  17190. * @returns A `Promise` that is resolved when the persistent storage is
  17191. * cleared. Otherwise, the promise is rejected with an error.
  17192. */ (e)) throw e;
  17193. N("Error enabling offline persistence. Falling back to persistence disabled: " + e),
  17194. s.reject(e);
  17195. }
  17196. })).then((() => s.promise));
  17197. }
  17198. function fh(t) {
  17199. if (t._initialized && !t._terminated) throw new L(B.FAILED_PRECONDITION, "Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");
  17200. const e = new q;
  17201. return t._queue.enqueueAndForgetEvenWhileRestricted((async () => {
  17202. try {
  17203. await async function(t) {
  17204. if (!bt.C()) return Promise.resolve();
  17205. const e = t + "main";
  17206. await bt.delete(e);
  17207. }
  17208. /**
  17209. * @license
  17210. * Copyright 2017 Google LLC
  17211. *
  17212. * Licensed under the Apache License, Version 2.0 (the "License");
  17213. * you may not use this file except in compliance with the License.
  17214. * You may obtain a copy of the License at
  17215. *
  17216. * http://www.apache.org/licenses/LICENSE-2.0
  17217. *
  17218. * Unless required by applicable law or agreed to in writing, software
  17219. * distributed under the License is distributed on an "AS IS" BASIS,
  17220. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17221. * See the License for the specific language governing permissions and
  17222. * limitations under the License.
  17223. */
  17224. /**
  17225. * Compares two array for equality using comparator. The method computes the
  17226. * intersection and invokes `onAdd` for every element that is in `after` but not
  17227. * `before`. `onRemove` is invoked for every element in `before` but missing
  17228. * from `after`.
  17229. *
  17230. * The method creates a copy of both `before` and `after` and runs in O(n log
  17231. * n), where n is the size of the two lists.
  17232. *
  17233. * @param before - The elements that exist in the original array.
  17234. * @param after - The elements to diff against the original array.
  17235. * @param comparator - The comparator for the elements in before and after.
  17236. * @param onAdd - A function to invoke for every element that is part of `
  17237. * after` but not `before`.
  17238. * @param onRemove - A function to invoke for every element that is part of
  17239. * `before` but not `after`.
  17240. */ (Fo(t._databaseId, t._persistenceKey)), e.resolve();
  17241. } catch (t) {
  17242. e.reject(t);
  17243. }
  17244. })), e.promise;
  17245. }
  17246. /**
  17247. * Waits until all currently pending writes for the active user have been
  17248. * acknowledged by the backend.
  17249. *
  17250. * The returned promise resolves immediately if there are no outstanding writes.
  17251. * Otherwise, the promise waits for all previously issued writes (including
  17252. * those written in a previous app session), but it does not wait for writes
  17253. * that were added after the function is called. If you want to wait for
  17254. * additional writes, call `waitForPendingWrites()` again.
  17255. *
  17256. * Any outstanding `waitForPendingWrites()` promises are rejected during user
  17257. * changes.
  17258. *
  17259. * @returns A `Promise` which resolves when all currently pending writes have been
  17260. * acknowledged by the backend.
  17261. */ function dh(t) {
  17262. return function(t) {
  17263. const e = new q;
  17264. return t.asyncQueue.enqueueAndForget((async () => kc(await Ua(t), e))), e.promise;
  17265. }(uh(t = fa(t, ih)));
  17266. }
  17267. /**
  17268. * Re-enables use of the network for this {@link Firestore} instance after a prior
  17269. * call to {@link disableNetwork}.
  17270. *
  17271. * @returns A `Promise` that is resolved once the network has been enabled.
  17272. */ function _h(t) {
  17273. return Qa(uh(t = fa(t, ih)));
  17274. }
  17275. /**
  17276. * Disables network usage for this instance. It can be re-enabled via {@link
  17277. * enableNetwork}. While the network is disabled, any snapshot listeners,
  17278. * `getDoc()` or `getDocs()` calls will return results from cache, and any write
  17279. * operations will be queued until the network is restored.
  17280. *
  17281. * @returns A `Promise` that is resolved once the network has been disabled.
  17282. */ function wh(t) {
  17283. return ja(uh(t = fa(t, ih)));
  17284. }
  17285. /**
  17286. * Terminates the provided {@link Firestore} instance.
  17287. *
  17288. * After calling `terminate()` only the `clearIndexedDbPersistence()` function
  17289. * may be used. Any other function will throw a `FirestoreError`.
  17290. *
  17291. * To restart after termination, create a new instance of FirebaseFirestore with
  17292. * {@link (getFirestore:1)}.
  17293. *
  17294. * Termination does not cancel any pending writes, and any promises that are
  17295. * awaiting a response from the server will not be resolved. If you have
  17296. * persistence enabled, the next time you start this instance, it will resume
  17297. * sending these writes to the server.
  17298. *
  17299. * Note: Under normal circumstances, calling `terminate()` is not required. This
  17300. * function is useful only when you want to force this instance to release all
  17301. * of its resources or in combination with `clearIndexedDbPersistence()` to
  17302. * ensure that all local state is destroyed between test runs.
  17303. *
  17304. * @returns A `Promise` that is resolved when the instance has been successfully
  17305. * terminated.
  17306. */ function mh(t) {
  17307. return _removeServiceInstance(t.app, "firestore", t._databaseId.database), t._delete();
  17308. }
  17309. /**
  17310. * Loads a Firestore bundle into the local cache.
  17311. *
  17312. * @param firestore - The {@link Firestore} instance to load bundles for.
  17313. * @param bundleData - An object representing the bundle to be loaded. Valid
  17314. * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.
  17315. *
  17316. * @returns A `LoadBundleTask` object, which notifies callers with progress
  17317. * updates, and completion or error events. It can be used as a
  17318. * `Promise<LoadBundleTaskProgress>`.
  17319. */ function gh(t, e) {
  17320. const n = uh(t = fa(t, ih)), s = new nh;
  17321. return Xa(n, t._databaseId, e, s), s;
  17322. }
  17323. /**
  17324. * Reads a Firestore {@link Query} from local cache, identified by the given
  17325. * name.
  17326. *
  17327. * The named queries are packaged into bundles on the server side (along
  17328. * with resulting documents), and loaded to local cache using `loadBundle`. Once
  17329. * in local cache, use this method to extract a {@link Query} by name.
  17330. *
  17331. * @param firestore - The {@link Firestore} instance to read the query from.
  17332. * @param name - The name of the query.
  17333. * @returns A `Promise` that is resolved with the Query or `null`.
  17334. */ function yh(t, e) {
  17335. return Za(uh(t = fa(t, ih)), e).then((e => e ? new pa(t, null, e.query) : null));
  17336. }
  17337. function ph(t) {
  17338. if (t._initialized || t._terminated) throw new L(B.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.");
  17339. }
  17340. /**
  17341. * @license
  17342. * Copyright 2020 Google LLC
  17343. *
  17344. * Licensed under the Apache License, Version 2.0 (the "License");
  17345. * you may not use this file except in compliance with the License.
  17346. * You may obtain a copy of the License at
  17347. *
  17348. * http://www.apache.org/licenses/LICENSE-2.0
  17349. *
  17350. * Unless required by applicable law or agreed to in writing, software
  17351. * distributed under the License is distributed on an "AS IS" BASIS,
  17352. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17353. * See the License for the specific language governing permissions and
  17354. * limitations under the License.
  17355. */
  17356. /**
  17357. * @license
  17358. * Copyright 2020 Google LLC
  17359. *
  17360. * Licensed under the Apache License, Version 2.0 (the "License");
  17361. * you may not use this file except in compliance with the License.
  17362. * You may obtain a copy of the License at
  17363. *
  17364. * http://www.apache.org/licenses/LICENSE-2.0
  17365. *
  17366. * Unless required by applicable law or agreed to in writing, software
  17367. * distributed under the License is distributed on an "AS IS" BASIS,
  17368. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17369. * See the License for the specific language governing permissions and
  17370. * limitations under the License.
  17371. */
  17372. /**
  17373. * An immutable object representing an array of bytes.
  17374. */
  17375. class Ih {
  17376. /** @hideconstructor */
  17377. constructor(t) {
  17378. this._byteString = t;
  17379. }
  17380. /**
  17381. * Creates a new `Bytes` object from the given Base64 string, converting it to
  17382. * bytes.
  17383. *
  17384. * @param base64 - The Base64 string used to create the `Bytes` object.
  17385. */ static fromBase64String(t) {
  17386. try {
  17387. return new Ih(Qt.fromBase64String(t));
  17388. } catch (t) {
  17389. throw new L(B.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + t);
  17390. }
  17391. }
  17392. /**
  17393. * Creates a new `Bytes` object from the given Uint8Array.
  17394. *
  17395. * @param array - The Uint8Array used to create the `Bytes` object.
  17396. */ static fromUint8Array(t) {
  17397. return new Ih(Qt.fromUint8Array(t));
  17398. }
  17399. /**
  17400. * Returns the underlying bytes as a Base64-encoded string.
  17401. *
  17402. * @returns The Base64-encoded string created from the `Bytes` object.
  17403. */ toBase64() {
  17404. return this._byteString.toBase64();
  17405. }
  17406. /**
  17407. * Returns the underlying bytes in a new `Uint8Array`.
  17408. *
  17409. * @returns The Uint8Array created from the `Bytes` object.
  17410. */ toUint8Array() {
  17411. return this._byteString.toUint8Array();
  17412. }
  17413. /**
  17414. * Returns a string representation of the `Bytes` object.
  17415. *
  17416. * @returns A string representation of the `Bytes` object.
  17417. */ toString() {
  17418. return "Bytes(base64: " + this.toBase64() + ")";
  17419. }
  17420. /**
  17421. * Returns true if this `Bytes` object is equal to the provided one.
  17422. *
  17423. * @param other - The `Bytes` object to compare against.
  17424. * @returns true if this `Bytes` object is equal to the provided one.
  17425. */ isEqual(t) {
  17426. return this._byteString.isEqual(t._byteString);
  17427. }
  17428. }
  17429. /**
  17430. * @license
  17431. * Copyright 2020 Google LLC
  17432. *
  17433. * Licensed under the Apache License, Version 2.0 (the "License");
  17434. * you may not use this file except in compliance with the License.
  17435. * You may obtain a copy of the License at
  17436. *
  17437. * http://www.apache.org/licenses/LICENSE-2.0
  17438. *
  17439. * Unless required by applicable law or agreed to in writing, software
  17440. * distributed under the License is distributed on an "AS IS" BASIS,
  17441. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17442. * See the License for the specific language governing permissions and
  17443. * limitations under the License.
  17444. */
  17445. /**
  17446. * A `FieldPath` refers to a field in a document. The path may consist of a
  17447. * single field name (referring to a top-level field in the document), or a
  17448. * list of field names (referring to a nested field in the document).
  17449. *
  17450. * Create a `FieldPath` by providing field names. If more than one field
  17451. * name is provided, the path will point to a nested field in a document.
  17452. */ class Th {
  17453. /**
  17454. * Creates a `FieldPath` from the provided field names. If more than one field
  17455. * name is provided, the path will point to a nested field in a document.
  17456. *
  17457. * @param fieldNames - A list of field names.
  17458. */
  17459. constructor(...t) {
  17460. for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new L(B.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty.");
  17461. this._internalPath = new ut(t);
  17462. }
  17463. /**
  17464. * Returns true if this `FieldPath` is equal to the provided one.
  17465. *
  17466. * @param other - The `FieldPath` to compare against.
  17467. * @returns true if this `FieldPath` is equal to the provided one.
  17468. */ isEqual(t) {
  17469. return this._internalPath.isEqual(t._internalPath);
  17470. }
  17471. }
  17472. /**
  17473. * Returns a special sentinel `FieldPath` to refer to the ID of a document.
  17474. * It can be used in queries to sort or filter by the document ID.
  17475. */ function Eh() {
  17476. return new Th("__name__");
  17477. }
  17478. /**
  17479. * @license
  17480. * Copyright 2020 Google LLC
  17481. *
  17482. * Licensed under the Apache License, Version 2.0 (the "License");
  17483. * you may not use this file except in compliance with the License.
  17484. * You may obtain a copy of the License at
  17485. *
  17486. * http://www.apache.org/licenses/LICENSE-2.0
  17487. *
  17488. * Unless required by applicable law or agreed to in writing, software
  17489. * distributed under the License is distributed on an "AS IS" BASIS,
  17490. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17491. * See the License for the specific language governing permissions and
  17492. * limitations under the License.
  17493. */
  17494. /**
  17495. * Sentinel values that can be used when writing document fields with `set()`
  17496. * or `update()`.
  17497. */ class Ah {
  17498. /**
  17499. * @param _methodName - The public API endpoint that returns this class.
  17500. * @hideconstructor
  17501. */
  17502. constructor(t) {
  17503. this._methodName = t;
  17504. }
  17505. }
  17506. /**
  17507. * @license
  17508. * Copyright 2017 Google LLC
  17509. *
  17510. * Licensed under the Apache License, Version 2.0 (the "License");
  17511. * you may not use this file except in compliance with the License.
  17512. * You may obtain a copy of the License at
  17513. *
  17514. * http://www.apache.org/licenses/LICENSE-2.0
  17515. *
  17516. * Unless required by applicable law or agreed to in writing, software
  17517. * distributed under the License is distributed on an "AS IS" BASIS,
  17518. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17519. * See the License for the specific language governing permissions and
  17520. * limitations under the License.
  17521. */
  17522. /**
  17523. * An immutable object representing a geographic location in Firestore. The
  17524. * location is represented as latitude/longitude pair.
  17525. *
  17526. * Latitude values are in the range of [-90, 90].
  17527. * Longitude values are in the range of [-180, 180].
  17528. */ class Rh {
  17529. /**
  17530. * Creates a new immutable `GeoPoint` object with the provided latitude and
  17531. * longitude values.
  17532. * @param latitude - The latitude as number between -90 and 90.
  17533. * @param longitude - The longitude as number between -180 and 180.
  17534. */
  17535. constructor(t, e) {
  17536. if (!isFinite(t) || t < -90 || t > 90) throw new L(B.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + t);
  17537. if (!isFinite(e) || e < -180 || e > 180) throw new L(B.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + e);
  17538. this._lat = t, this._long = e;
  17539. }
  17540. /**
  17541. * The latitude of this `GeoPoint` instance.
  17542. */ get latitude() {
  17543. return this._lat;
  17544. }
  17545. /**
  17546. * The longitude of this `GeoPoint` instance.
  17547. */ get longitude() {
  17548. return this._long;
  17549. }
  17550. /**
  17551. * Returns true if this `GeoPoint` is equal to the provided one.
  17552. *
  17553. * @param other - The `GeoPoint` to compare against.
  17554. * @returns true if this `GeoPoint` is equal to the provided one.
  17555. */ isEqual(t) {
  17556. return this._lat === t._lat && this._long === t._long;
  17557. }
  17558. /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() {
  17559. return {
  17560. latitude: this._lat,
  17561. longitude: this._long
  17562. };
  17563. }
  17564. /**
  17565. * Actually private to JS consumers of our API, so this function is prefixed
  17566. * with an underscore.
  17567. */ _compareTo(t) {
  17568. return Z(this._lat, t._lat) || Z(this._long, t._long);
  17569. }
  17570. }
  17571. /**
  17572. * @license
  17573. * Copyright 2017 Google LLC
  17574. *
  17575. * Licensed under the Apache License, Version 2.0 (the "License");
  17576. * you may not use this file except in compliance with the License.
  17577. * You may obtain a copy of the License at
  17578. *
  17579. * http://www.apache.org/licenses/LICENSE-2.0
  17580. *
  17581. * Unless required by applicable law or agreed to in writing, software
  17582. * distributed under the License is distributed on an "AS IS" BASIS,
  17583. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17584. * See the License for the specific language governing permissions and
  17585. * limitations under the License.
  17586. */ const bh = /^__.*__$/;
  17587. /** The result of parsing document data (e.g. for a setData call). */ class Ph {
  17588. constructor(t, e, n) {
  17589. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  17590. }
  17591. toMutation(t, e) {
  17592. return null !== this.fieldMask ? new ts(t, this.data, this.fieldMask, e, this.fieldTransforms) : new Zn(t, this.data, e, this.fieldTransforms);
  17593. }
  17594. }
  17595. /** The result of parsing "update" data (i.e. for an updateData call). */ class vh {
  17596. constructor(t,
  17597. // The fieldMask does not include document transforms.
  17598. e, n) {
  17599. this.data = t, this.fieldMask = e, this.fieldTransforms = n;
  17600. }
  17601. toMutation(t, e) {
  17602. return new ts(t, this.data, this.fieldMask, e, this.fieldTransforms);
  17603. }
  17604. }
  17605. function Vh(t) {
  17606. switch (t) {
  17607. case 0 /* UserDataSource.Set */ :
  17608. // fall through
  17609. case 2 /* UserDataSource.MergeSet */ :
  17610. // fall through
  17611. case 1 /* UserDataSource.Update */ :
  17612. return !0;
  17613. case 3 /* UserDataSource.Argument */ :
  17614. case 4 /* UserDataSource.ArrayArgument */ :
  17615. return !1;
  17616. default:
  17617. throw O();
  17618. }
  17619. }
  17620. /** A "context" object passed around while parsing user data. */ class Sh {
  17621. /**
  17622. * Initializes a ParseContext with the given source and path.
  17623. *
  17624. * @param settings - The settings for the parser.
  17625. * @param databaseId - The database ID of the Firestore instance.
  17626. * @param serializer - The serializer to use to generate the Value proto.
  17627. * @param ignoreUndefinedProperties - Whether to ignore undefined properties
  17628. * rather than throw.
  17629. * @param fieldTransforms - A mutable list of field transforms encountered
  17630. * while parsing the data.
  17631. * @param fieldMask - A mutable list of field paths encountered while parsing
  17632. * the data.
  17633. *
  17634. * TODO(b/34871131): We don't support array paths right now, so path can be
  17635. * null to indicate the context represents any location within an array (in
  17636. * which case certain features will not work and errors will be somewhat
  17637. * compromised).
  17638. */
  17639. constructor(t, e, n, s, i, r) {
  17640. this.settings = t, this.databaseId = e, this.yt = n, this.ignoreUndefinedProperties = s,
  17641. // Minor hack: If fieldTransforms is undefined, we assume this is an
  17642. // external call and we need to validate the entire path.
  17643. void 0 === i && this.na(), this.fieldTransforms = i || [], this.fieldMask = r || [];
  17644. }
  17645. get path() {
  17646. return this.settings.path;
  17647. }
  17648. get sa() {
  17649. return this.settings.sa;
  17650. }
  17651. /** Returns a new context with the specified settings overwritten. */ ia(t) {
  17652. return new Sh(Object.assign(Object.assign({}, this.settings), t), this.databaseId, this.yt, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);
  17653. }
  17654. ra(t) {
  17655. var e;
  17656. const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.ia({
  17657. path: n,
  17658. oa: !1
  17659. });
  17660. return s.ua(t), s;
  17661. }
  17662. ca(t) {
  17663. var e;
  17664. const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.ia({
  17665. path: n,
  17666. oa: !1
  17667. });
  17668. return s.na(), s;
  17669. }
  17670. aa(t) {
  17671. // TODO(b/34871131): We don't support array paths right now; so make path
  17672. // undefined.
  17673. return this.ia({
  17674. path: void 0,
  17675. oa: !0
  17676. });
  17677. }
  17678. ha(t) {
  17679. return Hh(t, this.settings.methodName, this.settings.la || !1, this.path, this.settings.fa);
  17680. }
  17681. /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) {
  17682. return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field)));
  17683. }
  17684. na() {
  17685. // TODO(b/34871131): Remove null check once we have proper paths for fields
  17686. // within arrays.
  17687. if (this.path) for (let t = 0; t < this.path.length; t++) this.ua(this.path.get(t));
  17688. }
  17689. ua(t) {
  17690. if (0 === t.length) throw this.ha("Document fields must not be empty");
  17691. if (Vh(this.sa) && bh.test(t)) throw this.ha('Document fields cannot begin and end with "__"');
  17692. }
  17693. }
  17694. /**
  17695. * Helper for parsing raw user input (provided via the API) into internal model
  17696. * classes.
  17697. */ class Dh {
  17698. constructor(t, e, n) {
  17699. this.databaseId = t, this.ignoreUndefinedProperties = e, this.yt = n || pu(t);
  17700. }
  17701. /** Creates a new top-level parse context. */ da(t, e, n, s = !1) {
  17702. return new Sh({
  17703. sa: t,
  17704. methodName: e,
  17705. fa: n,
  17706. path: ut.emptyPath(),
  17707. oa: !1,
  17708. la: s
  17709. }, this.databaseId, this.yt, this.ignoreUndefinedProperties);
  17710. }
  17711. }
  17712. function Ch(t) {
  17713. const e = t._freezeSettings(), n = pu(t._databaseId);
  17714. return new Dh(t._databaseId, !!e.ignoreUndefinedProperties, n);
  17715. }
  17716. /** Parse document data from a set() call. */ function xh(t, e, n, s, i, r = {}) {
  17717. const o = t.da(r.merge || r.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, n, i);
  17718. Qh("Data must be an object, but it was:", o, s);
  17719. const u = Kh(s, o);
  17720. let c, a;
  17721. if (r.merge) c = new Je(o.fieldMask), a = o.fieldTransforms; else if (r.mergeFields) {
  17722. const t = [];
  17723. for (const s of r.mergeFields) {
  17724. const i = jh(e, s, n);
  17725. if (!o.contains(i)) throw new L(B.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`);
  17726. Jh(t, i) || t.push(i);
  17727. }
  17728. c = new Je(t), a = o.fieldTransforms.filter((t => c.covers(t.field)));
  17729. } else c = null, a = o.fieldTransforms;
  17730. return new Ph(new Ye(u), c, a);
  17731. }
  17732. class Nh extends Ah {
  17733. _toFieldTransform(t) {
  17734. if (2 /* UserDataSource.MergeSet */ !== t.sa) throw 1 /* UserDataSource.Update */ === t.sa ? t.ha(`${this._methodName}() can only appear at the top level of your update data`) : t.ha(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);
  17735. // No transform to add for a delete, but we need to add it to our
  17736. // fieldMask so it gets deleted.
  17737. return t.fieldMask.push(t.path), null;
  17738. }
  17739. isEqual(t) {
  17740. return t instanceof Nh;
  17741. }
  17742. }
  17743. /**
  17744. * Creates a child context for parsing SerializableFieldValues.
  17745. *
  17746. * This is different than calling `ParseContext.contextWith` because it keeps
  17747. * the fieldTransforms and fieldMask separate.
  17748. *
  17749. * The created context has its `dataSource` set to `UserDataSource.Argument`.
  17750. * Although these values are used with writes, any elements in these FieldValues
  17751. * are not considered writes since they cannot contain any FieldValue sentinels,
  17752. * etc.
  17753. *
  17754. * @param fieldValue - The sentinel FieldValue for which to create a child
  17755. * context.
  17756. * @param context - The parent context.
  17757. * @param arrayElement - Whether or not the FieldValue has an array.
  17758. */ function kh(t, e, n) {
  17759. return new Sh({
  17760. sa: 3 /* UserDataSource.Argument */ ,
  17761. fa: e.settings.fa,
  17762. methodName: t._methodName,
  17763. oa: n
  17764. }, e.databaseId, e.yt, e.ignoreUndefinedProperties);
  17765. }
  17766. class Oh extends Ah {
  17767. _toFieldTransform(t) {
  17768. return new Un(t.path, new kn);
  17769. }
  17770. isEqual(t) {
  17771. return t instanceof Oh;
  17772. }
  17773. }
  17774. class Mh extends Ah {
  17775. constructor(t, e) {
  17776. super(t), this._a = e;
  17777. }
  17778. _toFieldTransform(t) {
  17779. const e = kh(this, t,
  17780. /*array=*/ !0), n = this._a.map((t => Uh(t, e))), s = new On(n);
  17781. return new Un(t.path, s);
  17782. }
  17783. isEqual(t) {
  17784. // TODO(mrschmidt): Implement isEquals
  17785. return this === t;
  17786. }
  17787. }
  17788. class Fh extends Ah {
  17789. constructor(t, e) {
  17790. super(t), this._a = e;
  17791. }
  17792. _toFieldTransform(t) {
  17793. const e = kh(this, t,
  17794. /*array=*/ !0), n = this._a.map((t => Uh(t, e))), s = new Fn(n);
  17795. return new Un(t.path, s);
  17796. }
  17797. isEqual(t) {
  17798. // TODO(mrschmidt): Implement isEquals
  17799. return this === t;
  17800. }
  17801. }
  17802. class $h extends Ah {
  17803. constructor(t, e) {
  17804. super(t), this.wa = e;
  17805. }
  17806. _toFieldTransform(t) {
  17807. const e = new Bn(t.yt, Sn(t.yt, this.wa));
  17808. return new Un(t.path, e);
  17809. }
  17810. isEqual(t) {
  17811. // TODO(mrschmidt): Implement isEquals
  17812. return this === t;
  17813. }
  17814. }
  17815. /** Parse update data from an update() call. */ function Bh(t, e, n, s) {
  17816. const i = t.da(1 /* UserDataSource.Update */ , e, n);
  17817. Qh("Data must be an object, but it was:", i, s);
  17818. const r = [], o = Ye.empty();
  17819. Bt(s, ((t, s) => {
  17820. const u = zh(e, t, n);
  17821. // For Compat types, we have to "extract" the underlying types before
  17822. // performing validation.
  17823. s = getModularInstance(s);
  17824. const c = i.ca(u);
  17825. if (s instanceof Nh)
  17826. // Add it to the field mask, but don't add anything to updateData.
  17827. r.push(u); else {
  17828. const t = Uh(s, c);
  17829. null != t && (r.push(u), o.set(u, t));
  17830. }
  17831. }));
  17832. const u = new Je(r);
  17833. return new vh(o, u, i.fieldTransforms);
  17834. }
  17835. /** Parse update data from a list of field/value arguments. */ function Lh(t, e, n, s, i, r) {
  17836. const o = t.da(1 /* UserDataSource.Update */ , e, n), u = [ jh(e, s, n) ], c = [ i ];
  17837. if (r.length % 2 != 0) throw new L(B.INVALID_ARGUMENT, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);
  17838. for (let t = 0; t < r.length; t += 2) u.push(jh(e, r[t])), c.push(r[t + 1]);
  17839. const a = [], h = Ye.empty();
  17840. // We iterate in reverse order to pick the last value for a field if the
  17841. // user specified the field multiple times.
  17842. for (let t = u.length - 1; t >= 0; --t) if (!Jh(a, u[t])) {
  17843. const e = u[t];
  17844. let n = c[t];
  17845. // For Compat types, we have to "extract" the underlying types before
  17846. // performing validation.
  17847. n = getModularInstance(n);
  17848. const s = o.ca(e);
  17849. if (n instanceof Nh)
  17850. // Add it to the field mask, but don't add anything to updateData.
  17851. a.push(e); else {
  17852. const t = Uh(n, s);
  17853. null != t && (a.push(e), h.set(e, t));
  17854. }
  17855. }
  17856. const l = new Je(a);
  17857. return new vh(h, l, o.fieldTransforms);
  17858. }
  17859. /**
  17860. * Parse a "query value" (e.g. value in a where filter or a value in a cursor
  17861. * bound).
  17862. *
  17863. * @param allowArrays - Whether the query value is an array that may directly
  17864. * contain additional arrays (e.g. the operand of an `in` query).
  17865. */ function qh(t, e, n, s = !1) {
  17866. return Uh(n, t.da(s ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e));
  17867. }
  17868. /**
  17869. * Parses user data to Protobuf Values.
  17870. *
  17871. * @param input - Data to be parsed.
  17872. * @param context - A context object representing the current path being parsed,
  17873. * the source of the data being parsed, etc.
  17874. * @returns The parsed value, or null if the value was a FieldValue sentinel
  17875. * that should not be included in the resulting parsed data.
  17876. */ function Uh(t, e) {
  17877. if (Gh(
  17878. // Unwrap the API type from the Compat SDK. This will return the API type
  17879. // from firestore-exp.
  17880. t = getModularInstance(t))) return Qh("Unsupported field value:", e, t), Kh(t, e);
  17881. if (t instanceof Ah)
  17882. // FieldValues usually parse into transforms (except deleteField())
  17883. // in which case we do not want to include this field in our parsed data
  17884. // (as doing so will overwrite the field directly prior to the transform
  17885. // trying to transform it). So we don't add this location to
  17886. // context.fieldMask and we return null as our parsing result.
  17887. /**
  17888. * "Parses" the provided FieldValueImpl, adding any necessary transforms to
  17889. * context.fieldTransforms.
  17890. */
  17891. return function(t, e) {
  17892. // Sentinels are only supported with writes, and not within arrays.
  17893. if (!Vh(e.sa)) throw e.ha(`${t._methodName}() can only be used with update() and set()`);
  17894. if (!e.path) throw e.ha(`${t._methodName}() is not currently supported inside arrays`);
  17895. const n = t._toFieldTransform(e);
  17896. n && e.fieldTransforms.push(n);
  17897. }
  17898. /**
  17899. * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)
  17900. *
  17901. * @returns The parsed value
  17902. */ (t, e), null;
  17903. if (void 0 === t && e.ignoreUndefinedProperties)
  17904. // If the input is undefined it can never participate in the fieldMask, so
  17905. // don't handle this below. If `ignoreUndefinedProperties` is false,
  17906. // `parseScalarValue` will reject an undefined value.
  17907. return null;
  17908. if (
  17909. // If context.path is null we are inside an array and we don't support
  17910. // field mask paths more granular than the top-level array.
  17911. e.path && e.fieldMask.push(e.path), t instanceof Array) {
  17912. // TODO(b/34871131): Include the path containing the array in the error
  17913. // message.
  17914. // In the case of IN queries, the parsed data is an array (representing
  17915. // the set of values to be included for the IN query) that may directly
  17916. // contain additional arrays (each representing an individual field
  17917. // value), so we disable this validation.
  17918. if (e.settings.oa && 4 /* UserDataSource.ArrayArgument */ !== e.sa) throw e.ha("Nested arrays are not supported");
  17919. return function(t, e) {
  17920. const n = [];
  17921. let s = 0;
  17922. for (const i of t) {
  17923. let t = Uh(i, e.aa(s));
  17924. null == t && (
  17925. // Just include nulls in the array for fields being replaced with a
  17926. // sentinel.
  17927. t = {
  17928. nullValue: "NULL_VALUE"
  17929. }), n.push(t), s++;
  17930. }
  17931. return {
  17932. arrayValue: {
  17933. values: n
  17934. }
  17935. };
  17936. }(t, e);
  17937. }
  17938. return function(t, e) {
  17939. if (null === (t = getModularInstance(t))) return {
  17940. nullValue: "NULL_VALUE"
  17941. };
  17942. if ("number" == typeof t) return Sn(e.yt, t);
  17943. if ("boolean" == typeof t) return {
  17944. booleanValue: t
  17945. };
  17946. if ("string" == typeof t) return {
  17947. stringValue: t
  17948. };
  17949. if (t instanceof Date) {
  17950. const n = nt.fromDate(t);
  17951. return {
  17952. timestampValue: $s(e.yt, n)
  17953. };
  17954. }
  17955. if (t instanceof nt) {
  17956. // Firestore backend truncates precision down to microseconds. To ensure
  17957. // offline mode works the same with regards to truncation, perform the
  17958. // truncation immediately without waiting for the backend to do that.
  17959. const n = new nt(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));
  17960. return {
  17961. timestampValue: $s(e.yt, n)
  17962. };
  17963. }
  17964. if (t instanceof Rh) return {
  17965. geoPointValue: {
  17966. latitude: t.latitude,
  17967. longitude: t.longitude
  17968. }
  17969. };
  17970. if (t instanceof Ih) return {
  17971. bytesValue: Bs(e.yt, t._byteString)
  17972. };
  17973. if (t instanceof ya) {
  17974. const n = e.databaseId, s = t.firestore._databaseId;
  17975. if (!s.isEqual(n)) throw e.ha(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${n.projectId}/${n.database}`);
  17976. return {
  17977. referenceValue: Us(t.firestore._databaseId || e.databaseId, t._key.path)
  17978. };
  17979. }
  17980. throw e.ha(`Unsupported field value: ${la(t)}`);
  17981. }
  17982. /**
  17983. * Checks whether an object looks like a JSON object that should be converted
  17984. * into a struct. Normal class/prototype instances are considered to look like
  17985. * JSON objects since they should be converted to a struct value. Arrays, Dates,
  17986. * GeoPoints, etc. are not considered to look like JSON objects since they map
  17987. * to specific FieldValue types other than ObjectValue.
  17988. */ (t, e);
  17989. }
  17990. function Kh(t, e) {
  17991. const n = {};
  17992. return Lt(t) ?
  17993. // If we encounter an empty object, we explicitly add it to the update
  17994. // mask to ensure that the server creates a map entry.
  17995. e.path && e.path.length > 0 && e.fieldMask.push(e.path) : Bt(t, ((t, s) => {
  17996. const i = Uh(s, e.ra(t));
  17997. null != i && (n[t] = i);
  17998. })), {
  17999. mapValue: {
  18000. fields: n
  18001. }
  18002. };
  18003. }
  18004. function Gh(t) {
  18005. return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof nt || t instanceof Rh || t instanceof Ih || t instanceof ya || t instanceof Ah);
  18006. }
  18007. function Qh(t, e, n) {
  18008. if (!Gh(n) || !function(t) {
  18009. return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));
  18010. }(n)) {
  18011. const s = la(n);
  18012. throw "an object" === s ? e.ha(t + " a custom object") : e.ha(t + " " + s);
  18013. }
  18014. }
  18015. /**
  18016. * Helper that calls fromDotSeparatedString() but wraps any error thrown.
  18017. */ function jh(t, e, n) {
  18018. if ((
  18019. // If required, replace the FieldPath Compat class with with the firestore-exp
  18020. // FieldPath.
  18021. e = getModularInstance(e)) instanceof Th) return e._internalPath;
  18022. if ("string" == typeof e) return zh(t, e);
  18023. throw Hh("Field path arguments must be of type string or ", t,
  18024. /* hasConverter= */ !1,
  18025. /* path= */ void 0, n);
  18026. }
  18027. /**
  18028. * Matches any characters in a field path string that are reserved.
  18029. */ const Wh = new RegExp("[~\\*/\\[\\]]");
  18030. /**
  18031. * Wraps fromDotSeparatedString with an error message about the method that
  18032. * was thrown.
  18033. * @param methodName - The publicly visible method name
  18034. * @param path - The dot-separated string form of a field path which will be
  18035. * split on dots.
  18036. * @param targetDoc - The document against which the field path will be
  18037. * evaluated.
  18038. */ function zh(t, e, n) {
  18039. if (e.search(Wh) >= 0) throw Hh(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t,
  18040. /* hasConverter= */ !1,
  18041. /* path= */ void 0, n);
  18042. try {
  18043. return new Th(...e.split("."))._internalPath;
  18044. } catch (s) {
  18045. throw Hh(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t,
  18046. /* hasConverter= */ !1,
  18047. /* path= */ void 0, n);
  18048. }
  18049. }
  18050. function Hh(t, e, n, s, i) {
  18051. const r = s && !s.isEmpty(), o = void 0 !== i;
  18052. let u = `Function ${e}() called with invalid data`;
  18053. n && (u += " (via `toFirestore()`)"), u += ". ";
  18054. let c = "";
  18055. return (r || o) && (c += " (found", r && (c += ` in field ${s}`), o && (c += ` in document ${i}`),
  18056. c += ")"), new L(B.INVALID_ARGUMENT, u + t + c);
  18057. }
  18058. /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function Jh(t, e) {
  18059. return t.some((t => t.isEqual(e)));
  18060. }
  18061. /**
  18062. * @license
  18063. * Copyright 2020 Google LLC
  18064. *
  18065. * Licensed under the Apache License, Version 2.0 (the "License");
  18066. * you may not use this file except in compliance with the License.
  18067. * You may obtain a copy of the License at
  18068. *
  18069. * http://www.apache.org/licenses/LICENSE-2.0
  18070. *
  18071. * Unless required by applicable law or agreed to in writing, software
  18072. * distributed under the License is distributed on an "AS IS" BASIS,
  18073. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18074. * See the License for the specific language governing permissions and
  18075. * limitations under the License.
  18076. */
  18077. /**
  18078. * A `DocumentSnapshot` contains data read from a document in your Firestore
  18079. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  18080. * get a specific field.
  18081. *
  18082. * For a `DocumentSnapshot` that points to a non-existing document, any data
  18083. * access will return 'undefined'. You can use the `exists()` method to
  18084. * explicitly verify a document's existence.
  18085. */ class Yh {
  18086. // Note: This class is stripped down version of the DocumentSnapshot in
  18087. // the legacy SDK. The changes are:
  18088. // - No support for SnapshotMetadata.
  18089. // - No support for SnapshotOptions.
  18090. /** @hideconstructor protected */
  18091. constructor(t, e, n, s, i) {
  18092. this._firestore = t, this._userDataWriter = e, this._key = n, this._document = s,
  18093. this._converter = i;
  18094. }
  18095. /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() {
  18096. return this._key.path.lastSegment();
  18097. }
  18098. /**
  18099. * The `DocumentReference` for the document included in the `DocumentSnapshot`.
  18100. */ get ref() {
  18101. return new ya(this._firestore, this._converter, this._key);
  18102. }
  18103. /**
  18104. * Signals whether or not the document at the snapshot's location exists.
  18105. *
  18106. * @returns true if the document exists.
  18107. */ exists() {
  18108. return null !== this._document;
  18109. }
  18110. /**
  18111. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  18112. * the document doesn't exist.
  18113. *
  18114. * @returns An `Object` containing all fields in the document or `undefined`
  18115. * if the document doesn't exist.
  18116. */ data() {
  18117. if (this._document) {
  18118. if (this._converter) {
  18119. // We only want to use the converter and create a new DocumentSnapshot
  18120. // if a converter has been provided.
  18121. const t = new Xh(this._firestore, this._userDataWriter, this._key, this._document,
  18122. /* converter= */ null);
  18123. return this._converter.fromFirestore(t);
  18124. }
  18125. return this._userDataWriter.convertValue(this._document.data.value);
  18126. }
  18127. }
  18128. /**
  18129. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  18130. * document or field doesn't exist.
  18131. *
  18132. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  18133. * field.
  18134. * @returns The data at the specified field location or undefined if no such
  18135. * field exists in the document.
  18136. */
  18137. // We are using `any` here to avoid an explicit cast by our users.
  18138. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  18139. get(t) {
  18140. if (this._document) {
  18141. const e = this._document.data.field(Zh("DocumentSnapshot.get", t));
  18142. if (null !== e) return this._userDataWriter.convertValue(e);
  18143. }
  18144. }
  18145. }
  18146. /**
  18147. * A `QueryDocumentSnapshot` contains data read from a document in your
  18148. * Firestore database as part of a query. The document is guaranteed to exist
  18149. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  18150. * specific field.
  18151. *
  18152. * A `QueryDocumentSnapshot` offers the same API surface as a
  18153. * `DocumentSnapshot`. Since query results contain only existing documents, the
  18154. * `exists` property will always be true and `data()` will never return
  18155. * 'undefined'.
  18156. */ class Xh extends Yh {
  18157. /**
  18158. * Retrieves all fields in the document as an `Object`.
  18159. *
  18160. * @override
  18161. * @returns An `Object` containing all fields in the document.
  18162. */
  18163. data() {
  18164. return super.data();
  18165. }
  18166. }
  18167. /**
  18168. * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.
  18169. */ function Zh(t, e) {
  18170. return "string" == typeof e ? zh(t, e) : e instanceof Th ? e._internalPath : e._delegate._internalPath;
  18171. }
  18172. /**
  18173. * @license
  18174. * Copyright 2020 Google LLC
  18175. *
  18176. * Licensed under the Apache License, Version 2.0 (the "License");
  18177. * you may not use this file except in compliance with the License.
  18178. * You may obtain a copy of the License at
  18179. *
  18180. * http://www.apache.org/licenses/LICENSE-2.0
  18181. *
  18182. * Unless required by applicable law or agreed to in writing, software
  18183. * distributed under the License is distributed on an "AS IS" BASIS,
  18184. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18185. * See the License for the specific language governing permissions and
  18186. * limitations under the License.
  18187. */ function tl(t) {
  18188. if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new L(B.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause");
  18189. }
  18190. /**
  18191. * An `AppliableConstraint` is an abstraction of a constraint that can be applied
  18192. * to a Firestore query.
  18193. */ class el {}
  18194. /**
  18195. * A `QueryConstraint` is used to narrow the set of documents returned by a
  18196. * Firestore query. `QueryConstraint`s are created by invoking {@link where},
  18197. * {@link orderBy}, {@link startAt}, {@link startAfter}, {@link
  18198. * endBefore}, {@link endAt}, {@link limit}, {@link limitToLast} and
  18199. * can then be passed to {@link query} to create a new query instance that
  18200. * also contains this `QueryConstraint`.
  18201. */ class nl extends el {}
  18202. function sl(t, e, ...n) {
  18203. let s = [];
  18204. e instanceof el && s.push(e), s = s.concat(n), function(t) {
  18205. const e = t.filter((t => t instanceof ol)).length, n = t.filter((t => t instanceof il)).length;
  18206. if (e > 1 || e > 0 && n > 0) throw new L(B.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(...)))`.");
  18207. }
  18208. /**
  18209. * @license
  18210. * Copyright 2020 Google LLC
  18211. *
  18212. * Licensed under the Apache License, Version 2.0 (the "License");
  18213. * you may not use this file except in compliance with the License.
  18214. * You may obtain a copy of the License at
  18215. *
  18216. * http://www.apache.org/licenses/LICENSE-2.0
  18217. *
  18218. * Unless required by applicable law or agreed to in writing, software
  18219. * distributed under the License is distributed on an "AS IS" BASIS,
  18220. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18221. * See the License for the specific language governing permissions and
  18222. * limitations under the License.
  18223. */
  18224. /**
  18225. * Converts Firestore's internal types to the JavaScript types that we expose
  18226. * to the user.
  18227. *
  18228. * @internal
  18229. */ (s);
  18230. for (const e of s) t = e._apply(t);
  18231. return t;
  18232. }
  18233. /**
  18234. * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
  18235. * a Firestore query by filtering on one or more document fields.
  18236. * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
  18237. * be passed to {@link query} to create a new query instance that also contains
  18238. * this `QueryFieldFilterConstraint`.
  18239. */ class il extends nl {
  18240. /**
  18241. * @internal
  18242. */
  18243. constructor(t, e, n) {
  18244. super(), this._field = t, this._op = e, this._value = n,
  18245. /** The type of this query constraint */
  18246. this.type = "where";
  18247. }
  18248. static _create(t, e, n) {
  18249. return new il(t, e, n);
  18250. }
  18251. _apply(t) {
  18252. const e = this._parse(t);
  18253. return Al(t._query, e), new pa(t.firestore, t.converter, yn(t._query, e));
  18254. }
  18255. _parse(t) {
  18256. const e = Ch(t.firestore), n = function(t, e, n, s, i, r, o) {
  18257. let u;
  18258. if (i.isKeyField()) {
  18259. if ("array-contains" /* Operator.ARRAY_CONTAINS */ === r || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === r) throw new L(B.INVALID_ARGUMENT, `Invalid Query. You can't perform '${r}' queries on documentId().`);
  18260. if ("in" /* Operator.IN */ === r || "not-in" /* Operator.NOT_IN */ === r) {
  18261. El(o, r);
  18262. const e = [];
  18263. for (const n of o) e.push(Tl(s, t, n));
  18264. u = {
  18265. arrayValue: {
  18266. values: e
  18267. }
  18268. };
  18269. } else u = Tl(s, t, o);
  18270. } else "in" /* Operator.IN */ !== r && "not-in" /* Operator.NOT_IN */ !== r && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== r || El(o, r),
  18271. u = qh(n, e, o,
  18272. /* allowArrays= */ "in" /* Operator.IN */ === r || "not-in" /* Operator.NOT_IN */ === r);
  18273. return Re.create(i, r, u);
  18274. }(t._query, "where", e, t.firestore._databaseId, this._field, this._op, this._value);
  18275. return n;
  18276. }
  18277. }
  18278. /**
  18279. * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
  18280. * must contain the specified field and that the value should satisfy the
  18281. * relation constraint provided.
  18282. *
  18283. * @param fieldPath - The path to compare
  18284. * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
  18285. * "&lt;=", "!=").
  18286. * @param value - The value for comparison
  18287. * @returns The created {@link QueryFieldFilterConstraint}.
  18288. */ function rl(t, e, n) {
  18289. const s = e, i = Zh("where", t);
  18290. return il._create(i, s, n);
  18291. }
  18292. /**
  18293. * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
  18294. * returned by a Firestore query by performing the logical OR or AND of multiple
  18295. * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
  18296. * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
  18297. * {@link and} and can then be passed to {@link query} to create a new query
  18298. * instance that also contains the `QueryCompositeFilterConstraint`.
  18299. * @internal TODO remove this internal tag with OR Query support in the server
  18300. */ class ol extends el {
  18301. /**
  18302. * @internal
  18303. */
  18304. constructor(
  18305. /** The type of this query constraint */
  18306. t, e) {
  18307. super(), this.type = t, this._queryConstraints = e;
  18308. }
  18309. static _create(t, e) {
  18310. return new ol(t, e);
  18311. }
  18312. _parse(t) {
  18313. const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0));
  18314. return 1 === e.length ? e[0] : be.create(e, this._getOperator());
  18315. }
  18316. _apply(t) {
  18317. const e = this._parse(t);
  18318. return 0 === e.getFilters().length ? t : (function(t, e) {
  18319. let n = t;
  18320. const s = e.getFlattenedFilters();
  18321. for (const t of s) Al(n, t), n = yn(n, t);
  18322. }
  18323. // Checks if any of the provided filter operators are included in the given list of filters and
  18324. // returns the first one that is, or null if none are.
  18325. (t._query, e), new pa(t.firestore, t.converter, yn(t._query, e)));
  18326. }
  18327. _getQueryConstraints() {
  18328. return this._queryConstraints;
  18329. }
  18330. _getOperator() {
  18331. return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */;
  18332. }
  18333. }
  18334. /**
  18335. * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of
  18336. * the given filter constraints. A disjunction filter includes a document if it
  18337. * satisfies any of the given filters.
  18338. *
  18339. * @param queryConstraints - Optional. The list of
  18340. * {@link QueryFilterConstraint}s to perform a disjunction for. These must be
  18341. * created with calls to {@link where}, {@link or}, or {@link and}.
  18342. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  18343. * @internal TODO remove this internal tag with OR Query support in the server
  18344. */ function ul(...t) {
  18345. // Only support QueryFilterConstraints
  18346. return t.forEach((t => bl("or", t))), ol._create("or" /* CompositeOperator.OR */ , t);
  18347. }
  18348. /**
  18349. * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of
  18350. * the given filter constraints. A conjunction filter includes a document if it
  18351. * satisfies all of the given filters.
  18352. *
  18353. * @param queryConstraints - Optional. The list of
  18354. * {@link QueryFilterConstraint}s to perform a conjunction for. These must be
  18355. * created with calls to {@link where}, {@link or}, or {@link and}.
  18356. * @returns The newly created {@link QueryCompositeFilterConstraint}.
  18357. * @internal TODO remove this internal tag with OR Query support in the server
  18358. */ function cl(...t) {
  18359. // Only support QueryFilterConstraints
  18360. return t.forEach((t => bl("and", t))), ol._create("and" /* CompositeOperator.AND */ , t);
  18361. }
  18362. /**
  18363. * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
  18364. * Firestore query. `QueryOrderByConstraint`s are created by invoking
  18365. * {@link orderBy} and can then be passed to {@link query} to create a new query
  18366. * instance that also contains this `QueryOrderByConstraint`.
  18367. *
  18368. * Note: Documents that do not contain the orderBy field will not be present in
  18369. * the query result.
  18370. */ class al extends nl {
  18371. /**
  18372. * @internal
  18373. */
  18374. constructor(t, e) {
  18375. super(), this._field = t, this._direction = e,
  18376. /** The type of this query constraint */
  18377. this.type = "orderBy";
  18378. }
  18379. static _create(t, e) {
  18380. return new al(t, e);
  18381. }
  18382. _apply(t) {
  18383. const e = function(t, e, n) {
  18384. if (null !== t.startAt) throw new L(B.INVALID_ARGUMENT, "Invalid query. You must not call startAt() or startAfter() before calling orderBy().");
  18385. if (null !== t.endAt) throw new L(B.INVALID_ARGUMENT, "Invalid query. You must not call endAt() or endBefore() before calling orderBy().");
  18386. const s = new Ue(e, n);
  18387. return function(t, e) {
  18388. if (null === dn(t)) {
  18389. // This is the first order by. It must match any inequality.
  18390. const n = _n(t);
  18391. null !== n && Rl(t, n, e.field);
  18392. }
  18393. }(t, s), s;
  18394. }
  18395. /**
  18396. * Create a `Bound` from a query and a document.
  18397. *
  18398. * Note that the `Bound` will always include the key of the document
  18399. * and so only the provided document will compare equal to the returned
  18400. * position.
  18401. *
  18402. * Will throw if the document does not contain all fields of the order by
  18403. * of the query or if any of the fields in the order by are an uncommitted
  18404. * server timestamp.
  18405. */ (t._query, this._field, this._direction);
  18406. return new pa(t.firestore, t.converter, function(t, e) {
  18407. // TODO(dimond): validate that orderBy does not list the same key twice.
  18408. const n = t.explicitOrderBy.concat([ e ]);
  18409. return new an(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);
  18410. }(t._query, e));
  18411. }
  18412. }
  18413. /**
  18414. * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
  18415. * specified field, optionally in descending order instead of ascending.
  18416. *
  18417. * Note: Documents that do not contain the specified field will not be present
  18418. * in the query result.
  18419. *
  18420. * @param fieldPath - The field to sort by.
  18421. * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
  18422. * not specified, order will be ascending.
  18423. * @returns The created {@link QueryOrderByConstraint}.
  18424. */ function hl(t, e = "asc") {
  18425. const n = e, s = Zh("orderBy", t);
  18426. return al._create(s, n);
  18427. }
  18428. /**
  18429. * A `QueryLimitConstraint` is used to limit the number of documents returned by
  18430. * a Firestore query.
  18431. * `QueryLimitConstraint`s are created by invoking {@link limit} or
  18432. * {@link limitToLast} and can then be passed to {@link query} to create a new
  18433. * query instance that also contains this `QueryLimitConstraint`.
  18434. */ class ll extends nl {
  18435. /**
  18436. * @internal
  18437. */
  18438. constructor(
  18439. /** The type of this query constraint */
  18440. t, e, n) {
  18441. super(), this.type = t, this._limit = e, this._limitType = n;
  18442. }
  18443. static _create(t, e, n) {
  18444. return new ll(t, e, n);
  18445. }
  18446. _apply(t) {
  18447. return new pa(t.firestore, t.converter, pn(t._query, this._limit, this._limitType));
  18448. }
  18449. }
  18450. /**
  18451. * Creates a {@link QueryLimitConstraint} that only returns the first matching
  18452. * documents.
  18453. *
  18454. * @param limit - The maximum number of items to return.
  18455. * @returns The created {@link QueryLimitConstraint}.
  18456. */ function fl(t) {
  18457. return da("limit", t), ll._create("limit", t, "F" /* LimitType.First */);
  18458. }
  18459. /**
  18460. * Creates a {@link QueryLimitConstraint} that only returns the last matching
  18461. * documents.
  18462. *
  18463. * You must specify at least one `orderBy` clause for `limitToLast` queries,
  18464. * otherwise an exception will be thrown during execution.
  18465. *
  18466. * @param limit - The maximum number of items to return.
  18467. * @returns The created {@link QueryLimitConstraint}.
  18468. */ function dl(t) {
  18469. return da("limitToLast", t), ll._create("limitToLast", t, "L" /* LimitType.Last */);
  18470. }
  18471. /**
  18472. * A `QueryStartAtConstraint` is used to exclude documents from the start of a
  18473. * result set returned by a Firestore query.
  18474. * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
  18475. * {@link (startAfter:1)} and can then be passed to {@link query} to create a
  18476. * new query instance that also contains this `QueryStartAtConstraint`.
  18477. */ class _l extends nl {
  18478. /**
  18479. * @internal
  18480. */
  18481. constructor(
  18482. /** The type of this query constraint */
  18483. t, e, n) {
  18484. super(), this.type = t, this._docOrFields = e, this._inclusive = n;
  18485. }
  18486. static _create(t, e, n) {
  18487. return new _l(t, e, n);
  18488. }
  18489. _apply(t) {
  18490. const e = Il(t, this.type, this._docOrFields, this._inclusive);
  18491. return new pa(t.firestore, t.converter, function(t, e) {
  18492. return new an(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt);
  18493. }(t._query, e));
  18494. }
  18495. }
  18496. function wl(...t) {
  18497. return _l._create("startAt", t,
  18498. /*inclusive=*/ !0);
  18499. }
  18500. function ml(...t) {
  18501. return _l._create("startAfter", t,
  18502. /*inclusive=*/ !1);
  18503. }
  18504. /**
  18505. * A `QueryEndAtConstraint` is used to exclude documents from the end of a
  18506. * result set returned by a Firestore query.
  18507. * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
  18508. * {@link (endBefore:1)} and can then be passed to {@link query} to create a new
  18509. * query instance that also contains this `QueryEndAtConstraint`.
  18510. */ class gl extends nl {
  18511. /**
  18512. * @internal
  18513. */
  18514. constructor(
  18515. /** The type of this query constraint */
  18516. t, e, n) {
  18517. super(), this.type = t, this._docOrFields = e, this._inclusive = n;
  18518. }
  18519. static _create(t, e, n) {
  18520. return new gl(t, e, n);
  18521. }
  18522. _apply(t) {
  18523. const e = Il(t, this.type, this._docOrFields, this._inclusive);
  18524. return new pa(t.firestore, t.converter, function(t, e) {
  18525. return new an(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e);
  18526. }(t._query, e));
  18527. }
  18528. }
  18529. function yl(...t) {
  18530. return gl._create("endBefore", t,
  18531. /*inclusive=*/ !1);
  18532. }
  18533. function pl(...t) {
  18534. return gl._create("endAt", t,
  18535. /*inclusive=*/ !0);
  18536. }
  18537. /** Helper function to create a bound from a document or fields */ function Il(t, e, n, s) {
  18538. if (n[0] = getModularInstance(n[0]), n[0] instanceof Yh) return function(t, e, n, s, i) {
  18539. if (!s) throw new L(B.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`);
  18540. const r = [];
  18541. // Because people expect to continue/end a query at the exact document
  18542. // provided, we need to use the implicit sort order rather than the explicit
  18543. // sort order, because it's guaranteed to contain the document key. That way
  18544. // the position becomes unambiguous and the query continues/ends exactly at
  18545. // the provided document. Without the key (by using the explicit sort
  18546. // orders), multiple documents could match the position, yielding duplicate
  18547. // results.
  18548. for (const n of mn(t)) if (n.field.isKeyField()) r.push(ce(e, s.key)); else {
  18549. const t = s.data.field(n.field);
  18550. if (Jt(t)) throw new L(B.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + n.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');
  18551. if (null === t) {
  18552. const t = n.field.canonicalString();
  18553. throw new L(B.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`);
  18554. }
  18555. r.push(t);
  18556. }
  18557. return new Ie(r, i);
  18558. }
  18559. /**
  18560. * Converts a list of field values to a `Bound` for the given query.
  18561. */ (t._query, t.firestore._databaseId, e, n[0]._document, s);
  18562. {
  18563. const i = Ch(t.firestore);
  18564. return function(t, e, n, s, i, r) {
  18565. // Use explicit order by's because it has to match the query the user made
  18566. const o = t.explicitOrderBy;
  18567. if (i.length > o.length) throw new L(B.INVALID_ARGUMENT, `Too many arguments provided to ${s}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);
  18568. const u = [];
  18569. for (let r = 0; r < i.length; r++) {
  18570. const c = i[r];
  18571. if (o[r].field.isKeyField()) {
  18572. if ("string" != typeof c) throw new L(B.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${s}(), but got a ${typeof c}`);
  18573. if (!wn(t) && -1 !== c.indexOf("/")) throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${s}() must be a plain document ID, but '${c}' contains a slash.`);
  18574. const n = t.path.child(rt.fromString(c));
  18575. if (!ct.isDocumentKey(n)) throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${s}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);
  18576. const i = new ct(n);
  18577. u.push(ce(e, i));
  18578. } else {
  18579. const t = qh(n, s, c);
  18580. u.push(t);
  18581. }
  18582. }
  18583. return new Ie(u, r);
  18584. }
  18585. /**
  18586. * Parses the given `documentIdValue` into a `ReferenceValue`, throwing
  18587. * appropriate errors if the value is anything other than a `DocumentReference`
  18588. * or `string`, or if the string is malformed.
  18589. */ (t._query, t.firestore._databaseId, i, e, n, s);
  18590. }
  18591. }
  18592. function Tl(t, e, n) {
  18593. if ("string" == typeof (n = getModularInstance(n))) {
  18594. if ("" === n) throw new L(B.INVALID_ARGUMENT, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");
  18595. if (!wn(e) && -1 !== n.indexOf("/")) throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);
  18596. const s = e.path.child(rt.fromString(n));
  18597. if (!ct.isDocumentKey(s)) throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${s}' is not because it has an odd number of segments (${s.length}).`);
  18598. return ce(t, new ct(s));
  18599. }
  18600. if (n instanceof ya) return ce(t, n._key);
  18601. throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${la(n)}.`);
  18602. }
  18603. /**
  18604. * Validates that the value passed into a disjunctive filter satisfies all
  18605. * array requirements.
  18606. */ function El(t, e) {
  18607. if (!Array.isArray(t) || 0 === t.length) throw new L(B.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`);
  18608. if (t.length > 10) throw new L(B.INVALID_ARGUMENT, `Invalid Query. '${e.toString()}' filters support a maximum of 10 elements in the value array.`);
  18609. }
  18610. /**
  18611. * Given an operator, returns the set of operators that cannot be used with it.
  18612. *
  18613. * Operators in a query must adhere to the following set of rules:
  18614. * 1. Only one array operator is allowed.
  18615. * 2. Only one disjunctive operator is allowed.
  18616. * 3. `NOT_EQUAL` cannot be used with another `NOT_EQUAL` operator.
  18617. * 4. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.
  18618. *
  18619. * Array operators: `ARRAY_CONTAINS`, `ARRAY_CONTAINS_ANY`
  18620. * Disjunctive operators: `IN`, `ARRAY_CONTAINS_ANY`, `NOT_IN`
  18621. */ function Al(t, e) {
  18622. if (e.isInequality()) {
  18623. const n = _n(t), s = e.field;
  18624. if (null !== n && !n.isEqual(s)) throw new L(B.INVALID_ARGUMENT, `Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${n.toString()}' and '${s.toString()}'`);
  18625. const i = dn(t);
  18626. null !== i && Rl(t, s, i);
  18627. }
  18628. const n = function(t, e) {
  18629. for (const n of t) for (const t of n.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op;
  18630. return null;
  18631. }(t.filters, function(t) {
  18632. switch (t) {
  18633. case "!=" /* Operator.NOT_EQUAL */ :
  18634. return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ];
  18635. case "array-contains" /* Operator.ARRAY_CONTAINS */ :
  18636. return [ "array-contains" /* Operator.ARRAY_CONTAINS */ , "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "not-in" /* Operator.NOT_IN */ ];
  18637. case "in" /* Operator.IN */ :
  18638. return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ ];
  18639. case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
  18640. return [ "array-contains" /* Operator.ARRAY_CONTAINS */ , "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ ];
  18641. case "not-in" /* Operator.NOT_IN */ :
  18642. return [ "array-contains" /* Operator.ARRAY_CONTAINS */ , "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ];
  18643. default:
  18644. return [];
  18645. }
  18646. }(e.op));
  18647. if (null !== n)
  18648. // Special case when it's a duplicate op to give a slightly clearer error message.
  18649. throw n === e.op ? new L(B.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new L(B.INVALID_ARGUMENT, `Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`);
  18650. }
  18651. function Rl(t, e, n) {
  18652. if (!n.isEqual(e)) throw new L(B.INVALID_ARGUMENT, `Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${e.toString()}' and so you must also use '${e.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`);
  18653. }
  18654. function bl(t, e) {
  18655. if (!(e instanceof il || e instanceof ol)) throw new L(B.INVALID_ARGUMENT, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);
  18656. }
  18657. class Pl {
  18658. convertValue(t, e = "none") {
  18659. switch (ee(t)) {
  18660. case 0 /* TypeOrder.NullValue */ :
  18661. return null;
  18662. case 1 /* TypeOrder.BooleanValue */ :
  18663. return t.booleanValue;
  18664. case 2 /* TypeOrder.NumberValue */ :
  18665. return zt(t.integerValue || t.doubleValue);
  18666. case 3 /* TypeOrder.TimestampValue */ :
  18667. return this.convertTimestamp(t.timestampValue);
  18668. case 4 /* TypeOrder.ServerTimestampValue */ :
  18669. return this.convertServerTimestamp(t, e);
  18670. case 5 /* TypeOrder.StringValue */ :
  18671. return t.stringValue;
  18672. case 6 /* TypeOrder.BlobValue */ :
  18673. return this.convertBytes(Ht(t.bytesValue));
  18674. case 7 /* TypeOrder.RefValue */ :
  18675. return this.convertReference(t.referenceValue);
  18676. case 8 /* TypeOrder.GeoPointValue */ :
  18677. return this.convertGeoPoint(t.geoPointValue);
  18678. case 9 /* TypeOrder.ArrayValue */ :
  18679. return this.convertArray(t.arrayValue, e);
  18680. case 10 /* TypeOrder.ObjectValue */ :
  18681. return this.convertObject(t.mapValue, e);
  18682. default:
  18683. throw O();
  18684. }
  18685. }
  18686. convertObject(t, e) {
  18687. const n = {};
  18688. return Bt(t.fields, ((t, s) => {
  18689. n[t] = this.convertValue(s, e);
  18690. })), n;
  18691. }
  18692. convertGeoPoint(t) {
  18693. return new Rh(zt(t.latitude), zt(t.longitude));
  18694. }
  18695. convertArray(t, e) {
  18696. return (t.values || []).map((t => this.convertValue(t, e)));
  18697. }
  18698. convertServerTimestamp(t, e) {
  18699. switch (e) {
  18700. case "previous":
  18701. const n = Yt(t);
  18702. return null == n ? null : this.convertValue(n, e);
  18703. case "estimate":
  18704. return this.convertTimestamp(Xt(t));
  18705. default:
  18706. return null;
  18707. }
  18708. }
  18709. convertTimestamp(t) {
  18710. const e = Wt(t);
  18711. return new nt(e.seconds, e.nanos);
  18712. }
  18713. convertDocumentKey(t, e) {
  18714. const n = rt.fromString(t);
  18715. M(wi(n));
  18716. const s = new Ft(n.get(1), n.get(3)), i = new ct(n.popFirst(5));
  18717. return s.isEqual(e) ||
  18718. // TODO(b/64130202): Somehow support foreign references.
  18719. x(`Document ${i} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`),
  18720. i;
  18721. }
  18722. }
  18723. /**
  18724. * @license
  18725. * Copyright 2020 Google LLC
  18726. *
  18727. * Licensed under the Apache License, Version 2.0 (the "License");
  18728. * you may not use this file except in compliance with the License.
  18729. * You may obtain a copy of the License at
  18730. *
  18731. * http://www.apache.org/licenses/LICENSE-2.0
  18732. *
  18733. * Unless required by applicable law or agreed to in writing, software
  18734. * distributed under the License is distributed on an "AS IS" BASIS,
  18735. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18736. * See the License for the specific language governing permissions and
  18737. * limitations under the License.
  18738. */
  18739. /**
  18740. * Converts custom model object of type T into `DocumentData` by applying the
  18741. * converter if it exists.
  18742. *
  18743. * This function is used when converting user objects to `DocumentData`
  18744. * because we want to provide the user with a more specific error message if
  18745. * their `set()` or fails due to invalid data originating from a `toFirestore()`
  18746. * call.
  18747. */ function vl(t, e, n) {
  18748. let s;
  18749. // Cast to `any` in order to satisfy the union type constraint on
  18750. // toFirestore().
  18751. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  18752. return s = t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e,
  18753. s;
  18754. }
  18755. class Vl extends Pl {
  18756. constructor(t) {
  18757. super(), this.firestore = t;
  18758. }
  18759. convertBytes(t) {
  18760. return new Ih(t);
  18761. }
  18762. convertReference(t) {
  18763. const e = this.convertDocumentKey(t, this.firestore._databaseId);
  18764. return new ya(this.firestore, /* converter= */ null, e);
  18765. }
  18766. }
  18767. /**
  18768. * @license
  18769. * Copyright 2020 Google LLC
  18770. *
  18771. * Licensed under the Apache License, Version 2.0 (the "License");
  18772. * you may not use this file except in compliance with the License.
  18773. * You may obtain a copy of the License at
  18774. *
  18775. * http://www.apache.org/licenses/LICENSE-2.0
  18776. *
  18777. * Unless required by applicable law or agreed to in writing, software
  18778. * distributed under the License is distributed on an "AS IS" BASIS,
  18779. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18780. * See the License for the specific language governing permissions and
  18781. * limitations under the License.
  18782. */
  18783. /**
  18784. * Metadata about a snapshot, describing the state of the snapshot.
  18785. */ class Sl {
  18786. /** @hideconstructor */
  18787. constructor(t, e) {
  18788. this.hasPendingWrites = t, this.fromCache = e;
  18789. }
  18790. /**
  18791. * Returns true if this `SnapshotMetadata` is equal to the provided one.
  18792. *
  18793. * @param other - The `SnapshotMetadata` to compare against.
  18794. * @returns true if this `SnapshotMetadata` is equal to the provided one.
  18795. */ isEqual(t) {
  18796. return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;
  18797. }
  18798. }
  18799. /**
  18800. * A `DocumentSnapshot` contains data read from a document in your Firestore
  18801. * database. The data can be extracted with `.data()` or `.get(<field>)` to
  18802. * get a specific field.
  18803. *
  18804. * For a `DocumentSnapshot` that points to a non-existing document, any data
  18805. * access will return 'undefined'. You can use the `exists()` method to
  18806. * explicitly verify a document's existence.
  18807. */ class Dl extends Yh {
  18808. /** @hideconstructor protected */
  18809. constructor(t, e, n, s, i, r) {
  18810. super(t, e, n, s, r), this._firestore = t, this._firestoreImpl = t, this.metadata = i;
  18811. }
  18812. /**
  18813. * Returns whether or not the data exists. True if the document exists.
  18814. */ exists() {
  18815. return super.exists();
  18816. }
  18817. /**
  18818. * Retrieves all fields in the document as an `Object`. Returns `undefined` if
  18819. * the document doesn't exist.
  18820. *
  18821. * By default, `serverTimestamp()` values that have not yet been
  18822. * set to their final value will be returned as `null`. You can override
  18823. * this by passing an options object.
  18824. *
  18825. * @param options - An options object to configure how data is retrieved from
  18826. * the snapshot (for example the desired behavior for server timestamps that
  18827. * have not yet been set to their final value).
  18828. * @returns An `Object` containing all fields in the document or `undefined` if
  18829. * the document doesn't exist.
  18830. */ data(t = {}) {
  18831. if (this._document) {
  18832. if (this._converter) {
  18833. // We only want to use the converter and create a new DocumentSnapshot
  18834. // if a converter has been provided.
  18835. const e = new Cl(this._firestore, this._userDataWriter, this._key, this._document, this.metadata,
  18836. /* converter= */ null);
  18837. return this._converter.fromFirestore(e, t);
  18838. }
  18839. return this._userDataWriter.convertValue(this._document.data.value, t.serverTimestamps);
  18840. }
  18841. }
  18842. /**
  18843. * Retrieves the field specified by `fieldPath`. Returns `undefined` if the
  18844. * document or field doesn't exist.
  18845. *
  18846. * By default, a `serverTimestamp()` that has not yet been set to
  18847. * its final value will be returned as `null`. You can override this by
  18848. * passing an options object.
  18849. *
  18850. * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
  18851. * field.
  18852. * @param options - An options object to configure how the field is retrieved
  18853. * from the snapshot (for example the desired behavior for server timestamps
  18854. * that have not yet been set to their final value).
  18855. * @returns The data at the specified field location or undefined if no such
  18856. * field exists in the document.
  18857. */
  18858. // We are using `any` here to avoid an explicit cast by our users.
  18859. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  18860. get(t, e = {}) {
  18861. if (this._document) {
  18862. const n = this._document.data.field(Zh("DocumentSnapshot.get", t));
  18863. if (null !== n) return this._userDataWriter.convertValue(n, e.serverTimestamps);
  18864. }
  18865. }
  18866. }
  18867. /**
  18868. * A `QueryDocumentSnapshot` contains data read from a document in your
  18869. * Firestore database as part of a query. The document is guaranteed to exist
  18870. * and its data can be extracted with `.data()` or `.get(<field>)` to get a
  18871. * specific field.
  18872. *
  18873. * A `QueryDocumentSnapshot` offers the same API surface as a
  18874. * `DocumentSnapshot`. Since query results contain only existing documents, the
  18875. * `exists` property will always be true and `data()` will never return
  18876. * 'undefined'.
  18877. */ class Cl extends Dl {
  18878. /**
  18879. * Retrieves all fields in the document as an `Object`.
  18880. *
  18881. * By default, `serverTimestamp()` values that have not yet been
  18882. * set to their final value will be returned as `null`. You can override
  18883. * this by passing an options object.
  18884. *
  18885. * @override
  18886. * @param options - An options object to configure how data is retrieved from
  18887. * the snapshot (for example the desired behavior for server timestamps that
  18888. * have not yet been set to their final value).
  18889. * @returns An `Object` containing all fields in the document.
  18890. */
  18891. data(t = {}) {
  18892. return super.data(t);
  18893. }
  18894. }
  18895. /**
  18896. * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
  18897. * representing the results of a query. The documents can be accessed as an
  18898. * array via the `docs` property or enumerated using the `forEach` method. The
  18899. * number of documents can be determined via the `empty` and `size`
  18900. * properties.
  18901. */ class xl {
  18902. /** @hideconstructor */
  18903. constructor(t, e, n, s) {
  18904. this._firestore = t, this._userDataWriter = e, this._snapshot = s, this.metadata = new Sl(s.hasPendingWrites, s.fromCache),
  18905. this.query = n;
  18906. }
  18907. /** An array of all the documents in the `QuerySnapshot`. */ get docs() {
  18908. const t = [];
  18909. return this.forEach((e => t.push(e))), t;
  18910. }
  18911. /** The number of documents in the `QuerySnapshot`. */ get size() {
  18912. return this._snapshot.docs.size;
  18913. }
  18914. /** True if there are no documents in the `QuerySnapshot`. */ get empty() {
  18915. return 0 === this.size;
  18916. }
  18917. /**
  18918. * Enumerates all of the documents in the `QuerySnapshot`.
  18919. *
  18920. * @param callback - A callback to be called with a `QueryDocumentSnapshot` for
  18921. * each document in the snapshot.
  18922. * @param thisArg - The `this` binding for the callback.
  18923. */ forEach(t, e) {
  18924. this._snapshot.docs.forEach((n => {
  18925. t.call(e, new Cl(this._firestore, this._userDataWriter, n.key, n, new Sl(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter));
  18926. }));
  18927. }
  18928. /**
  18929. * Returns an array of the documents changes since the last snapshot. If this
  18930. * is the first snapshot, all documents will be in the list as 'added'
  18931. * changes.
  18932. *
  18933. * @param options - `SnapshotListenOptions` that control whether metadata-only
  18934. * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
  18935. * snapshot events.
  18936. */ docChanges(t = {}) {
  18937. const e = !!t.includeMetadataChanges;
  18938. if (e && this._snapshot.excludesMetadataChanges) throw new L(B.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");
  18939. return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === e || (this._cachedChanges =
  18940. /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */
  18941. function(t, e) {
  18942. if (t._snapshot.oldDocs.isEmpty()) {
  18943. let e = 0;
  18944. return t._snapshot.docChanges.map((n => {
  18945. const s = new Cl(t._firestore, t._userDataWriter, n.doc.key, n.doc, new Sl(t._snapshot.mutatedKeys.has(n.doc.key), t._snapshot.fromCache), t.query.converter);
  18946. return n.doc, {
  18947. type: "added",
  18948. doc: s,
  18949. oldIndex: -1,
  18950. newIndex: e++
  18951. };
  18952. }));
  18953. }
  18954. {
  18955. // A `DocumentSet` that is updated incrementally as changes are applied to use
  18956. // to lookup the index of a document.
  18957. let n = t._snapshot.oldDocs;
  18958. return t._snapshot.docChanges.filter((t => e || 3 /* ChangeType.Metadata */ !== t.type)).map((e => {
  18959. const s = new Cl(t._firestore, t._userDataWriter, e.doc.key, e.doc, new Sl(t._snapshot.mutatedKeys.has(e.doc.key), t._snapshot.fromCache), t.query.converter);
  18960. let i = -1, r = -1;
  18961. return 0 /* ChangeType.Added */ !== e.type && (i = n.indexOf(e.doc.key), n = n.delete(e.doc.key)),
  18962. 1 /* ChangeType.Removed */ !== e.type && (n = n.add(e.doc), r = n.indexOf(e.doc.key)),
  18963. {
  18964. type: Nl(e.type),
  18965. doc: s,
  18966. oldIndex: i,
  18967. newIndex: r
  18968. };
  18969. }));
  18970. }
  18971. }(this, e), this._cachedChangesIncludeMetadataChanges = e), this._cachedChanges;
  18972. }
  18973. }
  18974. function Nl(t) {
  18975. switch (t) {
  18976. case 0 /* ChangeType.Added */ :
  18977. return "added";
  18978. case 2 /* ChangeType.Modified */ :
  18979. case 3 /* ChangeType.Metadata */ :
  18980. return "modified";
  18981. case 1 /* ChangeType.Removed */ :
  18982. return "removed";
  18983. default:
  18984. return O();
  18985. }
  18986. }
  18987. // TODO(firestoreexp): Add tests for snapshotEqual with different snapshot
  18988. // metadata
  18989. /**
  18990. * Returns true if the provided snapshots are equal.
  18991. *
  18992. * @param left - A snapshot to compare.
  18993. * @param right - A snapshot to compare.
  18994. * @returns true if the snapshots are equal.
  18995. */ function kl(t, e) {
  18996. return t instanceof Dl && e instanceof Dl ? 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 xl && e instanceof xl && (t._firestore === e._firestore && ba(t.query, e.query) && t.metadata.isEqual(e.metadata) && t._snapshot.isEqual(e._snapshot));
  18997. }
  18998. /**
  18999. * @license
  19000. * Copyright 2020 Google LLC
  19001. *
  19002. * Licensed under the Apache License, Version 2.0 (the "License");
  19003. * you may not use this file except in compliance with the License.
  19004. * You may obtain a copy of the License at
  19005. *
  19006. * http://www.apache.org/licenses/LICENSE-2.0
  19007. *
  19008. * Unless required by applicable law or agreed to in writing, software
  19009. * distributed under the License is distributed on an "AS IS" BASIS,
  19010. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19011. * See the License for the specific language governing permissions and
  19012. * limitations under the License.
  19013. */
  19014. /**
  19015. * Reads the document referred to by this `DocumentReference`.
  19016. *
  19017. * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting
  19018. * for data from the server, but it may return cached data or fail if you are
  19019. * offline and the server cannot be reached. To specify this behavior, invoke
  19020. * {@link getDocFromCache} or {@link getDocFromServer}.
  19021. *
  19022. * @param reference - The reference of the document to fetch.
  19023. * @returns A Promise resolved with a `DocumentSnapshot` containing the
  19024. * current document contents.
  19025. */ function Ol(t) {
  19026. t = fa(t, ya);
  19027. const e = fa(t.firestore, ih);
  19028. return za(uh(e), t._key).then((n => Hl(e, t, n)));
  19029. }
  19030. class Ml extends Pl {
  19031. constructor(t) {
  19032. super(), this.firestore = t;
  19033. }
  19034. convertBytes(t) {
  19035. return new Ih(t);
  19036. }
  19037. convertReference(t) {
  19038. const e = this.convertDocumentKey(t, this.firestore._databaseId);
  19039. return new ya(this.firestore, /* converter= */ null, e);
  19040. }
  19041. }
  19042. /**
  19043. * Reads the document referred to by this `DocumentReference` from cache.
  19044. * Returns an error if the document is not currently cached.
  19045. *
  19046. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  19047. * current document contents.
  19048. */ function Fl(t) {
  19049. t = fa(t, ya);
  19050. const e = fa(t.firestore, ih), n = uh(e), s = new Ml(e);
  19051. return Wa(n, t._key).then((n => new Dl(e, s, t._key, n, new Sl(null !== n && n.hasLocalMutations,
  19052. /* fromCache= */ !0), t.converter)));
  19053. }
  19054. /**
  19055. * Reads the document referred to by this `DocumentReference` from the server.
  19056. * Returns an error if the network is not available.
  19057. *
  19058. * @returns A `Promise` resolved with a `DocumentSnapshot` containing the
  19059. * current document contents.
  19060. */ function $l(t) {
  19061. t = fa(t, ya);
  19062. const e = fa(t.firestore, ih);
  19063. return za(uh(e), t._key, {
  19064. source: "server"
  19065. }).then((n => Hl(e, t, n)));
  19066. }
  19067. /**
  19068. * Executes the query and returns the results as a `QuerySnapshot`.
  19069. *
  19070. * Note: `getDocs()` attempts to provide up-to-date data when possible by
  19071. * waiting for data from the server, but it may return cached data or fail if
  19072. * you are offline and the server cannot be reached. To specify this behavior,
  19073. * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.
  19074. *
  19075. * @returns A `Promise` that will be resolved with the results of the query.
  19076. */ function Bl(t) {
  19077. t = fa(t, pa);
  19078. const e = fa(t.firestore, ih), n = uh(e), s = new Ml(e);
  19079. return tl(t._query), Ja(n, t._query).then((n => new xl(e, s, t, n)));
  19080. }
  19081. /**
  19082. * Executes the query and returns the results as a `QuerySnapshot` from cache.
  19083. * Returns an empty result set if no documents matching the query are currently
  19084. * cached.
  19085. *
  19086. * @returns A `Promise` that will be resolved with the results of the query.
  19087. */ function Ll(t) {
  19088. t = fa(t, pa);
  19089. const e = fa(t.firestore, ih), n = uh(e), s = new Ml(e);
  19090. return Ha(n, t._query).then((n => new xl(e, s, t, n)));
  19091. }
  19092. /**
  19093. * Executes the query and returns the results as a `QuerySnapshot` from the
  19094. * server. Returns an error if the network is not available.
  19095. *
  19096. * @returns A `Promise` that will be resolved with the results of the query.
  19097. */ function ql(t) {
  19098. t = fa(t, pa);
  19099. const e = fa(t.firestore, ih), n = uh(e), s = new Ml(e);
  19100. return Ja(n, t._query, {
  19101. source: "server"
  19102. }).then((n => new xl(e, s, t, n)));
  19103. }
  19104. function Ul(t, e, n) {
  19105. t = fa(t, ya);
  19106. const s = fa(t.firestore, ih), i = vl(t.converter, e, n);
  19107. return zl(s, [ xh(Ch(s), "setDoc", t._key, i, null !== t.converter, n).toMutation(t._key, Qn.none()) ]);
  19108. }
  19109. function Kl(t, e, n, ...s) {
  19110. t = fa(t, ya);
  19111. const i = fa(t.firestore, ih), r = Ch(i);
  19112. let o;
  19113. o = "string" == typeof (
  19114. // For Compat types, we have to "extract" the underlying types before
  19115. // performing validation.
  19116. e = getModularInstance(e)) || e instanceof Th ? Lh(r, "updateDoc", t._key, e, n, s) : Bh(r, "updateDoc", t._key, e);
  19117. return zl(i, [ o.toMutation(t._key, Qn.exists(!0)) ]);
  19118. }
  19119. /**
  19120. * Deletes the document referred to by the specified `DocumentReference`.
  19121. *
  19122. * @param reference - A reference to the document to delete.
  19123. * @returns A Promise resolved once the document has been successfully
  19124. * deleted from the backend (note that it won't resolve while you're offline).
  19125. */ function Gl(t) {
  19126. return zl(fa(t.firestore, ih), [ new is(t._key, Qn.none()) ]);
  19127. }
  19128. /**
  19129. * Add a new document to specified `CollectionReference` with the given data,
  19130. * assigning it a document ID automatically.
  19131. *
  19132. * @param reference - A reference to the collection to add this document to.
  19133. * @param data - An Object containing the data for the new document.
  19134. * @returns A `Promise` resolved with a `DocumentReference` pointing to the
  19135. * newly created document after it has been written to the backend (Note that it
  19136. * won't resolve while you're offline).
  19137. */ function Ql(t, e) {
  19138. const n = fa(t.firestore, ih), s = Aa(t), i = vl(t.converter, e);
  19139. return zl(n, [ xh(Ch(t.firestore), "addDoc", s._key, i, null !== t.converter, {}).toMutation(s._key, Qn.exists(!1)) ]).then((() => s));
  19140. }
  19141. function jl(t, ...e) {
  19142. var n, s, i;
  19143. t = getModularInstance(t);
  19144. let r = {
  19145. includeMetadataChanges: !1
  19146. }, o = 0;
  19147. "object" != typeof e[o] || eh(e[o]) || (r = e[o], o++);
  19148. const u = {
  19149. includeMetadataChanges: r.includeMetadataChanges
  19150. };
  19151. if (eh(e[o])) {
  19152. const t = e[o];
  19153. e[o] = null === (n = t.next) || void 0 === n ? void 0 : n.bind(t), e[o + 1] = null === (s = t.error) || void 0 === s ? void 0 : s.bind(t),
  19154. e[o + 2] = null === (i = t.complete) || void 0 === i ? void 0 : i.bind(t);
  19155. }
  19156. let c, a, h;
  19157. if (t instanceof ya) a = fa(t.firestore, ih), h = ln(t._key.path), c = {
  19158. next: n => {
  19159. e[o] && e[o](Hl(a, t, n));
  19160. },
  19161. error: e[o + 1],
  19162. complete: e[o + 2]
  19163. }; else {
  19164. const n = fa(t, pa);
  19165. a = fa(n.firestore, ih), h = n._query;
  19166. const s = new Ml(a);
  19167. c = {
  19168. next: t => {
  19169. e[o] && e[o](new xl(a, s, n, t));
  19170. },
  19171. error: e[o + 1],
  19172. complete: e[o + 2]
  19173. }, tl(t._query);
  19174. }
  19175. return function(t, e, n, s) {
  19176. const i = new va(s), r = new _c(e, i, n);
  19177. return t.asyncQueue.enqueueAndForget((async () => ac(await Ga(t), r))), () => {
  19178. i.bc(), t.asyncQueue.enqueueAndForget((async () => hc(await Ga(t), r)));
  19179. };
  19180. }(uh(a), h, u, c);
  19181. }
  19182. function Wl(t, e) {
  19183. return Ya(uh(t = fa(t, ih)), eh(e) ? e : {
  19184. next: e
  19185. });
  19186. }
  19187. /**
  19188. * Locally writes `mutations` on the async queue.
  19189. * @internal
  19190. */ function zl(t, e) {
  19191. return function(t, e) {
  19192. const n = new q;
  19193. return t.asyncQueue.enqueueAndForget((async () => Vc(await Ua(t), e, n))), n.promise;
  19194. }(uh(t), e);
  19195. }
  19196. /**
  19197. * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`
  19198. * to a {@link DocumentSnapshot}.
  19199. */ function Hl(t, e, n) {
  19200. const s = n.docs.get(e._key), i = new Ml(t);
  19201. return new Dl(t, i, e._key, s, new Sl(n.hasPendingWrites, n.fromCache), e.converter);
  19202. }
  19203. /**
  19204. * @license
  19205. * Copyright 2022 Google LLC
  19206. *
  19207. * Licensed under the Apache License, Version 2.0 (the "License");
  19208. * you may not use this file except in compliance with the License.
  19209. * You may obtain a copy of the License at
  19210. *
  19211. * http://www.apache.org/licenses/LICENSE-2.0
  19212. *
  19213. * Unless required by applicable law or agreed to in writing, software
  19214. * distributed under the License is distributed on an "AS IS" BASIS,
  19215. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19216. * See the License for the specific language governing permissions and
  19217. * limitations under the License.
  19218. */
  19219. /**
  19220. * Compares two `AggregateQuerySnapshot` instances for equality.
  19221. *
  19222. * Two `AggregateQuerySnapshot` instances are considered "equal" if they have
  19223. * underlying queries that compare equal, and the same data.
  19224. *
  19225. * @param left - The first `AggregateQuerySnapshot` to compare.
  19226. * @param right - The second `AggregateQuerySnapshot` to compare.
  19227. *
  19228. * @returns `true` if the objects are "equal", as defined above, or `false`
  19229. * otherwise.
  19230. */ function Jl(t, e) {
  19231. return ba(t.query, e.query) && deepEqual(t.data(), e.data());
  19232. }
  19233. /**
  19234. * @license
  19235. * Copyright 2022 Google LLC
  19236. *
  19237. * Licensed under the Apache License, Version 2.0 (the "License");
  19238. * you may not use this file except in compliance with the License.
  19239. * You may obtain a copy of the License at
  19240. *
  19241. * http://www.apache.org/licenses/LICENSE-2.0
  19242. *
  19243. * Unless required by applicable law or agreed to in writing, software
  19244. * distributed under the License is distributed on an "AS IS" BASIS,
  19245. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19246. * See the License for the specific language governing permissions and
  19247. * limitations under the License.
  19248. */
  19249. /**
  19250. * Calculates the number of documents in the result set of the given query,
  19251. * without actually downloading the documents.
  19252. *
  19253. * Using this function to count the documents is efficient because only the
  19254. * final count, not the documents' data, is downloaded. This function can even
  19255. * count the documents if the result set would be prohibitively large to
  19256. * download entirely (e.g. thousands of documents).
  19257. *
  19258. * The result received from the server is presented, unaltered, without
  19259. * considering any local state. That is, documents in the local cache are not
  19260. * taken into consideration, neither are local modifications not yet
  19261. * synchronized with the server. Previously-downloaded results, if any, are not
  19262. * used: every request using this source necessarily involves a round trip to
  19263. * the server.
  19264. *
  19265. * @param query - The query whose result set size to calculate.
  19266. * @returns A Promise that will be resolved with the count; the count can be
  19267. * retrieved from `snapshot.data().count`, where `snapshot` is the
  19268. * `AggregateQuerySnapshot` to which the returned Promise resolves.
  19269. */ function Yl(t) {
  19270. const e = fa(t.firestore, ih);
  19271. return function(t, e, n) {
  19272. const s = new q;
  19273. return t.asyncQueue.enqueueAndForget((async () => {
  19274. try {
  19275. if (Mu(await qa(t))) {
  19276. const i = await Ka(t), r = new Ca(e, i, n).run();
  19277. s.resolve(r);
  19278. } else s.reject(new L(B.UNAVAILABLE, "Failed to get count result because the client is offline."));
  19279. } catch (t) {
  19280. s.reject(t);
  19281. }
  19282. })), s.promise;
  19283. }(uh(e), t, new Ml(e));
  19284. }
  19285. /**
  19286. * @license
  19287. * Copyright 2022 Google LLC
  19288. *
  19289. * Licensed under the Apache License, Version 2.0 (the "License");
  19290. * you may not use this file except in compliance with the License.
  19291. * You may obtain a copy of the License at
  19292. *
  19293. * http://www.apache.org/licenses/LICENSE-2.0
  19294. *
  19295. * Unless required by applicable law or agreed to in writing, software
  19296. * distributed under the License is distributed on an "AS IS" BASIS,
  19297. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19298. * See the License for the specific language governing permissions and
  19299. * limitations under the License.
  19300. */ const Xl = {
  19301. maxAttempts: 5
  19302. };
  19303. /**
  19304. * @license
  19305. * Copyright 2020 Google LLC
  19306. *
  19307. * Licensed under the Apache License, Version 2.0 (the "License");
  19308. * you may not use this file except in compliance with the License.
  19309. * You may obtain a copy of the License at
  19310. *
  19311. * http://www.apache.org/licenses/LICENSE-2.0
  19312. *
  19313. * Unless required by applicable law or agreed to in writing, software
  19314. * distributed under the License is distributed on an "AS IS" BASIS,
  19315. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19316. * See the License for the specific language governing permissions and
  19317. * limitations under the License.
  19318. */
  19319. /**
  19320. * A write batch, used to perform multiple writes as a single atomic unit.
  19321. *
  19322. * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It
  19323. * provides methods for adding writes to the write batch. None of the writes
  19324. * will be committed (or visible locally) until {@link WriteBatch.commit} is
  19325. * called.
  19326. */
  19327. class Zl {
  19328. /** @hideconstructor */
  19329. constructor(t, e) {
  19330. this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1,
  19331. this._dataReader = Ch(t);
  19332. }
  19333. set(t, e, n) {
  19334. this._verifyNotCommitted();
  19335. const s = tf(t, this._firestore), i = vl(s.converter, e, n), r = xh(this._dataReader, "WriteBatch.set", s._key, i, null !== s.converter, n);
  19336. return this._mutations.push(r.toMutation(s._key, Qn.none())), this;
  19337. }
  19338. update(t, e, n, ...s) {
  19339. this._verifyNotCommitted();
  19340. const i = tf(t, this._firestore);
  19341. // For Compat types, we have to "extract" the underlying types before
  19342. // performing validation.
  19343. let r;
  19344. return r = "string" == typeof (e = getModularInstance(e)) || e instanceof Th ? Lh(this._dataReader, "WriteBatch.update", i._key, e, n, s) : Bh(this._dataReader, "WriteBatch.update", i._key, e),
  19345. this._mutations.push(r.toMutation(i._key, Qn.exists(!0))), this;
  19346. }
  19347. /**
  19348. * Deletes the document referred to by the provided {@link DocumentReference}.
  19349. *
  19350. * @param documentRef - A reference to the document to be deleted.
  19351. * @returns This `WriteBatch` instance. Used for chaining method calls.
  19352. */ delete(t) {
  19353. this._verifyNotCommitted();
  19354. const e = tf(t, this._firestore);
  19355. return this._mutations = this._mutations.concat(new is(e._key, Qn.none())), this;
  19356. }
  19357. /**
  19358. * Commits all of the writes in this write batch as a single atomic unit.
  19359. *
  19360. * The result of these writes will only be reflected in document reads that
  19361. * occur after the returned promise resolves. If the client is offline, the
  19362. * write fails. If you would like to see local modifications or buffer writes
  19363. * until the client is online, use the full Firestore SDK.
  19364. *
  19365. * @returns A `Promise` resolved once all of the writes in the batch have been
  19366. * successfully written to the backend as an atomic unit (note that it won't
  19367. * resolve while you're offline).
  19368. */ commit() {
  19369. return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();
  19370. }
  19371. _verifyNotCommitted() {
  19372. if (this._committed) throw new L(B.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called.");
  19373. }
  19374. }
  19375. function tf(t, e) {
  19376. if ((t = getModularInstance(t)).firestore !== e) throw new L(B.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance.");
  19377. return t;
  19378. }
  19379. /**
  19380. * @license
  19381. * Copyright 2020 Google LLC
  19382. *
  19383. * Licensed under the Apache License, Version 2.0 (the "License");
  19384. * you may not use this file except in compliance with the License.
  19385. * You may obtain a copy of the License at
  19386. *
  19387. * http://www.apache.org/licenses/LICENSE-2.0
  19388. *
  19389. * Unless required by applicable law or agreed to in writing, software
  19390. * distributed under the License is distributed on an "AS IS" BASIS,
  19391. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19392. * See the License for the specific language governing permissions and
  19393. * limitations under the License.
  19394. */
  19395. // TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the
  19396. // legacy SDK.
  19397. /**
  19398. * A reference to a transaction.
  19399. *
  19400. * The `Transaction` object passed to a transaction's `updateFunction` provides
  19401. * the methods to read and write data within the transaction context. See
  19402. * {@link runTransaction}.
  19403. */
  19404. /**
  19405. * @license
  19406. * Copyright 2020 Google LLC
  19407. *
  19408. * Licensed under the Apache License, Version 2.0 (the "License");
  19409. * you may not use this file except in compliance with the License.
  19410. * You may obtain a copy of the License at
  19411. *
  19412. * http://www.apache.org/licenses/LICENSE-2.0
  19413. *
  19414. * Unless required by applicable law or agreed to in writing, software
  19415. * distributed under the License is distributed on an "AS IS" BASIS,
  19416. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19417. * See the License for the specific language governing permissions and
  19418. * limitations under the License.
  19419. */
  19420. /**
  19421. * A reference to a transaction.
  19422. *
  19423. * The `Transaction` object passed to a transaction's `updateFunction` provides
  19424. * the methods to read and write data within the transaction context. See
  19425. * {@link runTransaction}.
  19426. */
  19427. class ef extends class {
  19428. /** @hideconstructor */
  19429. constructor(t, e) {
  19430. this._firestore = t, this._transaction = e, this._dataReader = Ch(t);
  19431. }
  19432. /**
  19433. * Reads the document referenced by the provided {@link DocumentReference}.
  19434. *
  19435. * @param documentRef - A reference to the document to be read.
  19436. * @returns A `DocumentSnapshot` with the read data.
  19437. */ get(t) {
  19438. const e = tf(t, this._firestore), n = new Vl(this._firestore);
  19439. return this._transaction.lookup([ e._key ]).then((t => {
  19440. if (!t || 1 !== t.length) return O();
  19441. const s = t[0];
  19442. if (s.isFoundDocument()) return new Yh(this._firestore, n, s.key, s, e.converter);
  19443. if (s.isNoDocument()) return new Yh(this._firestore, n, e._key, null, e.converter);
  19444. throw O();
  19445. }));
  19446. }
  19447. set(t, e, n) {
  19448. const s = tf(t, this._firestore), i = vl(s.converter, e, n), r = xh(this._dataReader, "Transaction.set", s._key, i, null !== s.converter, n);
  19449. return this._transaction.set(s._key, r), this;
  19450. }
  19451. update(t, e, n, ...s) {
  19452. const i = tf(t, this._firestore);
  19453. // For Compat types, we have to "extract" the underlying types before
  19454. // performing validation.
  19455. let r;
  19456. return r = "string" == typeof (e = getModularInstance(e)) || e instanceof Th ? Lh(this._dataReader, "Transaction.update", i._key, e, n, s) : Bh(this._dataReader, "Transaction.update", i._key, e),
  19457. this._transaction.update(i._key, r), this;
  19458. }
  19459. /**
  19460. * Deletes the document referred to by the provided {@link DocumentReference}.
  19461. *
  19462. * @param documentRef - A reference to the document to be deleted.
  19463. * @returns This `Transaction` instance. Used for chaining method calls.
  19464. */ delete(t) {
  19465. const e = tf(t, this._firestore);
  19466. return this._transaction.delete(e._key), this;
  19467. }
  19468. } {
  19469. // This class implements the same logic as the Transaction API in the Lite SDK
  19470. // but is subclassed in order to return its own DocumentSnapshot types.
  19471. /** @hideconstructor */
  19472. constructor(t, e) {
  19473. super(t, e), this._firestore = t;
  19474. }
  19475. /**
  19476. * Reads the document referenced by the provided {@link DocumentReference}.
  19477. *
  19478. * @param documentRef - A reference to the document to be read.
  19479. * @returns A `DocumentSnapshot` with the read data.
  19480. */ get(t) {
  19481. const e = tf(t, this._firestore), n = new Ml(this._firestore);
  19482. return super.get(t).then((t => new Dl(this._firestore, n, e._key, t._document, new Sl(
  19483. /* hasPendingWrites= */ !1,
  19484. /* fromCache= */ !1), e.converter)));
  19485. }
  19486. }
  19487. /**
  19488. * Executes the given `updateFunction` and then attempts to commit the changes
  19489. * applied within the transaction. If any document read within the transaction
  19490. * has changed, Cloud Firestore retries the `updateFunction`. If it fails to
  19491. * commit after 5 attempts, the transaction fails.
  19492. *
  19493. * The maximum number of writes allowed in a single transaction is 500.
  19494. *
  19495. * @param firestore - A reference to the Firestore database to run this
  19496. * transaction against.
  19497. * @param updateFunction - The function to execute within the transaction
  19498. * context.
  19499. * @param options - An options object to configure maximum number of attempts to
  19500. * commit.
  19501. * @returns If the transaction completed successfully or was explicitly aborted
  19502. * (the `updateFunction` returned a failed promise), the promise returned by the
  19503. * `updateFunction `is returned here. Otherwise, if the transaction failed, a
  19504. * rejected promise with the corresponding failure error is returned.
  19505. */ function nf(t, e, n) {
  19506. t = fa(t, ih);
  19507. const s = Object.assign(Object.assign({}, Xl), n);
  19508. !function(t) {
  19509. if (t.maxAttempts < 1) throw new L(B.INVALID_ARGUMENT, "Max attempts must be at least 1");
  19510. }(s);
  19511. return function(t, e, n) {
  19512. const s = new q;
  19513. return t.asyncQueue.enqueueAndForget((async () => {
  19514. const i = await Ka(t);
  19515. new Na(t.asyncQueue, i, n, e, s).run();
  19516. })), s.promise;
  19517. }(uh(t), (n => e(new ef(t, n))), s);
  19518. }
  19519. /**
  19520. * @license
  19521. * Copyright 2020 Google LLC
  19522. *
  19523. * Licensed under the Apache License, Version 2.0 (the "License");
  19524. * you may not use this file except in compliance with the License.
  19525. * You may obtain a copy of the License at
  19526. *
  19527. * http://www.apache.org/licenses/LICENSE-2.0
  19528. *
  19529. * Unless required by applicable law or agreed to in writing, software
  19530. * distributed under the License is distributed on an "AS IS" BASIS,
  19531. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19532. * See the License for the specific language governing permissions and
  19533. * limitations under the License.
  19534. */
  19535. /**
  19536. * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
  19537. * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
  19538. */ function sf() {
  19539. return new Nh("deleteField");
  19540. }
  19541. /**
  19542. * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
  19543. * include a server-generated timestamp in the written data.
  19544. */ function rf() {
  19545. return new Oh("serverTimestamp");
  19546. }
  19547. /**
  19548. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  19549. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
  19550. * value that already exists on the server. Each specified element that doesn't
  19551. * already exist in the array will be added to the end. If the field being
  19552. * modified is not already an array it will be overwritten with an array
  19553. * containing exactly the specified elements.
  19554. *
  19555. * @param elements - The elements to union into the array.
  19556. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  19557. * `updateDoc()`.
  19558. */ function of(...t) {
  19559. // NOTE: We don't actually parse the data until it's used in set() or
  19560. // update() since we'd need the Firestore instance to do this.
  19561. return new Mh("arrayUnion", t);
  19562. }
  19563. /**
  19564. * Returns a special value that can be used with {@link (setDoc:1)} or {@link
  19565. * updateDoc:1} that tells the server to remove the given elements from any
  19566. * array value that already exists on the server. All instances of each element
  19567. * specified will be removed from the array. If the field being modified is not
  19568. * already an array it will be overwritten with an empty array.
  19569. *
  19570. * @param elements - The elements to remove from the array.
  19571. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  19572. * `updateDoc()`
  19573. */ function uf(...t) {
  19574. // NOTE: We don't actually parse the data until it's used in set() or
  19575. // update() since we'd need the Firestore instance to do this.
  19576. return new Fh("arrayRemove", t);
  19577. }
  19578. /**
  19579. * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
  19580. * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
  19581. * the given value.
  19582. *
  19583. * If either the operand or the current field value uses floating point
  19584. * precision, all arithmetic follows IEEE 754 semantics. If both values are
  19585. * integers, values outside of JavaScript's safe number range
  19586. * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
  19587. * precision loss. Furthermore, once processed by the Firestore backend, all
  19588. * integer operations are capped between -2^63 and 2^63-1.
  19589. *
  19590. * If the current field value is not of type `number`, or if the field does not
  19591. * yet exist, the transformation sets the field to the given value.
  19592. *
  19593. * @param n - The value to increment by.
  19594. * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
  19595. * `updateDoc()`
  19596. */ function cf(t) {
  19597. return new $h("increment", t);
  19598. }
  19599. /**
  19600. * @license
  19601. * Copyright 2020 Google LLC
  19602. *
  19603. * Licensed under the Apache License, Version 2.0 (the "License");
  19604. * you may not use this file except in compliance with the License.
  19605. * You may obtain a copy of the License at
  19606. *
  19607. * http://www.apache.org/licenses/LICENSE-2.0
  19608. *
  19609. * Unless required by applicable law or agreed to in writing, software
  19610. * distributed under the License is distributed on an "AS IS" BASIS,
  19611. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19612. * See the License for the specific language governing permissions and
  19613. * limitations under the License.
  19614. */
  19615. /**
  19616. * Creates a write batch, used for performing multiple writes as a single
  19617. * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}
  19618. * is 500.
  19619. *
  19620. * Unlike transactions, write batches are persisted offline and therefore are
  19621. * preferable when you don't need to condition your writes on read data.
  19622. *
  19623. * @returns A {@link WriteBatch} that can be used to atomically execute multiple
  19624. * writes.
  19625. */ function af(t) {
  19626. return uh(t = fa(t, ih)), new Zl(t, (e => zl(t, e)));
  19627. }
  19628. /**
  19629. * @license
  19630. * Copyright 2021 Google LLC
  19631. *
  19632. * Licensed under the Apache License, Version 2.0 (the "License");
  19633. * you may not use this file except in compliance with the License.
  19634. * You may obtain a copy of the License at
  19635. *
  19636. * http://www.apache.org/licenses/LICENSE-2.0
  19637. *
  19638. * Unless required by applicable law or agreed to in writing, software
  19639. * distributed under the License is distributed on an "AS IS" BASIS,
  19640. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19641. * See the License for the specific language governing permissions and
  19642. * limitations under the License.
  19643. */ function hf(t, e) {
  19644. var n;
  19645. const s = uh(t = fa(t, ih));
  19646. // PORTING NOTE: We don't return an error if the user has not enabled
  19647. // persistence since `enableIndexeddbPersistence()` can fail on the Web.
  19648. if (!(null === (n = s.offlineComponents) || void 0 === n ? void 0 : n.indexBackfillerScheduler)) return N("Cannot enable indexes when persistence is disabled"),
  19649. Promise.resolve();
  19650. const i = function(t) {
  19651. const e = "string" == typeof t ? function(t) {
  19652. try {
  19653. return JSON.parse(t);
  19654. } catch (t) {
  19655. throw new L(B.INVALID_ARGUMENT, "Failed to parse JSON: " + (null == t ? void 0 : t.message));
  19656. }
  19657. }(t) : t, n = [];
  19658. if (Array.isArray(e.indexes)) for (const t of e.indexes) {
  19659. const e = lf(t, "collectionGroup"), s = [];
  19660. if (Array.isArray(t.fields)) for (const e of t.fields) {
  19661. const t = zh("setIndexConfiguration", lf(e, "fieldPath"));
  19662. "CONTAINS" === e.arrayConfig ? s.push(new dt(t, 2 /* IndexKind.CONTAINS */)) : "ASCENDING" === e.order ? s.push(new dt(t, 0 /* IndexKind.ASCENDING */)) : "DESCENDING" === e.order && s.push(new dt(t, 1 /* IndexKind.DESCENDING */));
  19663. }
  19664. n.push(new at(at.UNKNOWN_ID, e, s, wt.empty()));
  19665. }
  19666. return n;
  19667. }(e);
  19668. return La(s).then((t => async function(t, e) {
  19669. const n = $(t), s = n.indexManager, i = [];
  19670. return n.persistence.runTransaction("Configure indexes", "readwrite", (t => s.getFieldIndexes(t).next((n => function(t, e, n, s, i) {
  19671. t = [ ...t ], e = [ ...e ], t.sort(n), e.sort(n);
  19672. const r = t.length, o = e.length;
  19673. let u = 0, c = 0;
  19674. for (;u < o && c < r; ) {
  19675. const r = n(t[c], e[u]);
  19676. r < 0 ?
  19677. // The element was removed if the next element in our ordered
  19678. // walkthrough is only in `before`.
  19679. i(t[c++]) : r > 0 ?
  19680. // The element was added if the next element in our ordered walkthrough
  19681. // is only in `after`.
  19682. s(e[u++]) : (u++, c++);
  19683. }
  19684. for (;u < o; ) s(e[u++]);
  19685. for (;c < r; ) i(t[c++]);
  19686. }(n, e, ft, (e => {
  19687. i.push(s.addFieldIndex(t, e));
  19688. }), (e => {
  19689. i.push(s.deleteFieldIndex(t, e));
  19690. })))).next((() => At.waitFor(i)))));
  19691. }
  19692. /**
  19693. * @license
  19694. * Copyright 2019 Google LLC
  19695. *
  19696. * Licensed under the Apache License, Version 2.0 (the "License");
  19697. * you may not use this file except in compliance with the License.
  19698. * You may obtain a copy of the License at
  19699. *
  19700. * http://www.apache.org/licenses/LICENSE-2.0
  19701. *
  19702. * Unless required by applicable law or agreed to in writing, software
  19703. * distributed under the License is distributed on an "AS IS" BASIS,
  19704. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19705. * See the License for the specific language governing permissions and
  19706. * limitations under the License.
  19707. */
  19708. // The format of the LocalStorage key that stores the client state is:
  19709. // firestore_clients_<persistence_prefix>_<instance_key>
  19710. (t, i)));
  19711. }
  19712. function lf(t, e) {
  19713. if ("string" != typeof t[e]) throw new L(B.INVALID_ARGUMENT, "Missing string value for: " + e);
  19714. return t[e];
  19715. }
  19716. /**
  19717. * Cloud Firestore
  19718. *
  19719. * @packageDocumentation
  19720. */ !function(t, e = !0) {
  19721. !function(t) {
  19722. v = t;
  19723. }(SDK_VERSION), _registerComponent(new Component("firestore", ((t, {instanceIdentifier: n, options: s}) => {
  19724. const i = t.getProvider("app").getImmediate(), r = new ih(new Q(t.getProvider("auth-internal")), new H(t.getProvider("app-check-internal")), function(t, e) {
  19725. if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new L(B.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
  19726. return new Ft(t.options.projectId, e);
  19727. }(i, n), i);
  19728. return s = Object.assign({
  19729. useFetchStreams: e
  19730. }, s), r._setSettings(s), r;
  19731. }), "PUBLIC").setMultipleInstances(!0)), registerVersion(b, "3.8.1", t),
  19732. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  19733. registerVersion(b, "3.8.1", "esm2017");
  19734. }();
  19735. export { Pl as AbstractUserDataWriter, Sa as AggregateField, Da as AggregateQuerySnapshot, Ih as Bytes, sh as CACHE_SIZE_UNLIMITED, Ia as CollectionReference, ya as DocumentReference, Dl as DocumentSnapshot, Th as FieldPath, Ah as FieldValue, ih as Firestore, L as FirestoreError, Rh as GeoPoint, nh as LoadBundleTask, pa as Query, ol as QueryCompositeFilterConstraint, nl as QueryConstraint, Cl as QueryDocumentSnapshot, gl as QueryEndAtConstraint, il as QueryFieldFilterConstraint, ll as QueryLimitConstraint, al as QueryOrderByConstraint, xl as QuerySnapshot, _l as QueryStartAtConstraint, Sl as SnapshotMetadata, nt as Timestamp, ef as Transaction, Zl as WriteBatch, Ft as _DatabaseId, ct as _DocumentKey, J as _EmptyAppCheckTokenProvider, K as _EmptyAuthCredentialsProvider, ut as _FieldPath, fa as _cast, F as _debugAssert, Gt as _isBase64Available, N as _logWarn, ca as _validateIsNotUsedTogether, Ql as addDoc, Jl as aggregateQuerySnapshotEqual, cl as and, uf as arrayRemove, of as arrayUnion, fh as clearIndexedDbPersistence, Ta as collection, Ea as collectionGroup, ga as connectFirestoreEmulator, Gl as deleteDoc, sf as deleteField, wh as disableNetwork, Aa as doc, Eh as documentId, ah as enableIndexedDbPersistence, hh as enableMultiTabIndexedDbPersistence, _h as enableNetwork, pl as endAt, yl as endBefore, uh as ensureFirestoreConfigured, zl as executeWrite, Yl as getCountFromServer, Ol as getDoc, Fl as getDocFromCache, $l as getDocFromServer, Bl as getDocs, Ll as getDocsFromCache, ql as getDocsFromServer, oh as getFirestore, cf as increment, rh as initializeFirestore, fl as limit, dl as limitToLast, gh as loadBundle, yh as namedQuery, jl as onSnapshot, Wl as onSnapshotsInSync, ul as or, hl as orderBy, sl as query, ba as queryEqual, Ra as refEqual, nf as runTransaction, rf as serverTimestamp, Ul as setDoc, hf as setIndexConfiguration, D as setLogLevel, kl as snapshotEqual, ml as startAfter, wl as startAt, mh as terminate, Kl as updateDoc, dh as waitForPendingWrites, rl as where, af as writeBatch };
  19736. //# sourceMappingURL=index.esm2017.js.map