@firebase/firestore 3.7.3-canary.ab3f16cba → 3.7.3-canary.fde5adf63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/firestore/lite/index.d.ts +1 -1
  2. package/dist/firestore/src/api/filter.d.ts +1 -1
  3. package/dist/firestore/src/api.d.ts +1 -1
  4. package/dist/firestore/src/core/bound.d.ts +49 -0
  5. package/dist/firestore/src/core/filter.d.ts +134 -0
  6. package/dist/firestore/src/core/order_by.d.ts +35 -0
  7. package/dist/firestore/src/core/query.d.ts +5 -6
  8. package/dist/firestore/src/core/target.d.ts +4 -120
  9. package/dist/firestore/src/lite-api/query.d.ts +273 -66
  10. package/dist/firestore/src/local/indexeddb_index_manager.d.ts +2 -0
  11. package/dist/firestore/src/protos/firestore_proto_api.d.ts +1 -1
  12. package/dist/firestore/src/remote/serializer.d.ts +10 -3
  13. package/dist/firestore/src/util/logic_utils.d.ts +52 -0
  14. package/dist/firestore/test/unit/core/filter.test.d.ts +17 -0
  15. package/dist/firestore/test/unit/util/logic_utils.test.d.ts +17 -0
  16. package/dist/firestore/test/util/helpers.d.ts +5 -1
  17. package/dist/index.d.ts +138 -62
  18. package/dist/index.esm2017.js +4046 -3512
  19. package/dist/index.esm2017.js.map +1 -1
  20. package/dist/index.esm5.js +4366 -3816
  21. package/dist/index.esm5.js.map +1 -1
  22. package/dist/index.node.cjs.js +1291 -555
  23. package/dist/index.node.cjs.js.map +1 -1
  24. package/dist/index.node.mjs +1284 -556
  25. package/dist/index.node.mjs.map +1 -1
  26. package/dist/index.rn.js +4145 -3611
  27. package/dist/index.rn.js.map +1 -1
  28. package/dist/internal.d.ts +320 -65
  29. package/dist/lite/firestore/lite/index.d.ts +1 -1
  30. package/dist/lite/firestore/src/api/filter.d.ts +1 -1
  31. package/dist/lite/firestore/src/api.d.ts +1 -1
  32. package/dist/lite/firestore/src/core/bound.d.ts +49 -0
  33. package/dist/lite/firestore/src/core/filter.d.ts +134 -0
  34. package/dist/lite/firestore/src/core/order_by.d.ts +35 -0
  35. package/dist/lite/firestore/src/core/query.d.ts +5 -6
  36. package/dist/lite/firestore/src/core/target.d.ts +4 -120
  37. package/dist/lite/firestore/src/lite-api/query.d.ts +273 -66
  38. package/dist/lite/firestore/src/local/indexeddb_index_manager.d.ts +2 -0
  39. package/dist/lite/firestore/src/protos/firestore_proto_api.d.ts +1 -1
  40. package/dist/lite/firestore/src/remote/serializer.d.ts +10 -3
  41. package/dist/lite/firestore/src/util/logic_utils.d.ts +52 -0
  42. package/dist/lite/firestore/test/unit/core/filter.test.d.ts +17 -0
  43. package/dist/lite/firestore/test/unit/util/logic_utils.test.d.ts +17 -0
  44. package/dist/lite/firestore/test/util/helpers.d.ts +5 -1
  45. package/dist/lite/index.browser.esm2017.js +2119 -1843
  46. package/dist/lite/index.browser.esm2017.js.map +1 -1
  47. package/dist/lite/index.browser.esm5.js +1957 -1737
  48. package/dist/lite/index.browser.esm5.js.map +1 -1
  49. package/dist/lite/index.d.ts +138 -62
  50. package/dist/lite/index.node.cjs.js +2093 -1717
  51. package/dist/lite/index.node.cjs.js.map +1 -1
  52. package/dist/lite/index.node.mjs +2086 -1718
  53. package/dist/lite/index.node.mjs.map +1 -1
  54. package/dist/lite/index.rn.esm2017.js +2118 -1841
  55. package/dist/lite/index.rn.esm2017.js.map +1 -1
  56. package/dist/lite/internal.d.ts +320 -65
  57. package/dist/lite/packages/firestore/dist/lite/index.browser.esm2017.d.ts +320 -175
  58. package/dist/lite/packages/firestore/lite/index.d.ts +1 -1
  59. package/dist/lite/packages/firestore/src/api/filter.d.ts +1 -1
  60. package/dist/lite/packages/firestore/src/api.d.ts +1 -1
  61. package/dist/lite/packages/firestore/src/core/bound.d.ts +49 -0
  62. package/dist/lite/packages/firestore/src/core/filter.d.ts +134 -0
  63. package/dist/lite/packages/firestore/src/core/order_by.d.ts +35 -0
  64. package/dist/lite/packages/firestore/src/core/query.d.ts +5 -6
  65. package/dist/lite/packages/firestore/src/core/target.d.ts +4 -120
  66. package/dist/lite/packages/firestore/src/lite-api/query.d.ts +273 -66
  67. package/dist/lite/packages/firestore/src/local/indexeddb_index_manager.d.ts +2 -0
  68. package/dist/lite/packages/firestore/src/protos/firestore_proto_api.d.ts +1 -1
  69. package/dist/lite/packages/firestore/src/remote/serializer.d.ts +10 -3
  70. package/dist/lite/packages/firestore/src/util/logic_utils.d.ts +52 -0
  71. package/dist/lite/packages/firestore/test/unit/core/filter.test.d.ts +17 -0
  72. package/dist/lite/packages/firestore/test/unit/util/logic_utils.test.d.ts +17 -0
  73. package/dist/lite/packages/firestore/test/util/helpers.d.ts +5 -1
  74. package/dist/lite/private.d.ts +232 -65
  75. package/dist/packages/firestore/dist/index.esm2017.d.ts +333 -209
  76. package/dist/packages/firestore/lite/index.d.ts +1 -1
  77. package/dist/packages/firestore/src/api/filter.d.ts +1 -1
  78. package/dist/packages/firestore/src/api.d.ts +1 -1
  79. package/dist/packages/firestore/src/core/bound.d.ts +49 -0
  80. package/dist/packages/firestore/src/core/filter.d.ts +134 -0
  81. package/dist/packages/firestore/src/core/order_by.d.ts +35 -0
  82. package/dist/packages/firestore/src/core/query.d.ts +5 -6
  83. package/dist/packages/firestore/src/core/target.d.ts +4 -120
  84. package/dist/packages/firestore/src/lite-api/query.d.ts +273 -66
  85. package/dist/packages/firestore/src/local/indexeddb_index_manager.d.ts +2 -0
  86. package/dist/packages/firestore/src/protos/firestore_proto_api.d.ts +1 -1
  87. package/dist/packages/firestore/src/remote/serializer.d.ts +10 -3
  88. package/dist/packages/firestore/src/util/logic_utils.d.ts +52 -0
  89. package/dist/packages/firestore/test/unit/core/filter.test.d.ts +17 -0
  90. package/dist/packages/firestore/test/unit/util/logic_utils.test.d.ts +17 -0
  91. package/dist/packages/firestore/test/util/helpers.d.ts +5 -1
  92. package/dist/private.d.ts +232 -65
  93. package/package.json +11 -9
@@ -14,7 +14,7 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
14
14
 
15
15
  var nodeFetch__default = /*#__PURE__*/_interopDefaultLegacy(nodeFetch);
16
16
 
17
- const version$1 = "3.7.3-canary.ab3f16cba";
17
+ const version$1 = "3.7.3-canary.fde5adf63";
18
18
 
19
19
  /**
20
20
  * @license
@@ -67,7 +67,7 @@ User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');
67
67
  User.FIRST_PARTY = new User('first-party-uid');
68
68
  User.MOCK_USER = new User('mock-user');
69
69
 
70
- const version = "9.14.0-canary.ab3f16cba";
70
+ const version = "9.14.0-canary.fde5adf63";
71
71
 
72
72
  /**
73
73
  * @license
@@ -1613,159 +1613,29 @@ function arrayEquals(left, right, comparator) {
1613
1613
  * See the License for the specific language governing permissions and
1614
1614
  * limitations under the License.
1615
1615
  */
1616
- // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
1617
- const MIN_SECONDS = -62135596800;
1618
- // Number of nanoseconds in a millisecond.
1619
- const MS_TO_NANOS = 1e6;
1620
- /**
1621
- * A `Timestamp` represents a point in time independent of any time zone or
1622
- * calendar, represented as seconds and fractions of seconds at nanosecond
1623
- * resolution in UTC Epoch time.
1624
- *
1625
- * It is encoded using the Proleptic Gregorian Calendar which extends the
1626
- * Gregorian calendar backwards to year one. It is encoded assuming all minutes
1627
- * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
1628
- * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
1629
- * 9999-12-31T23:59:59.999999999Z.
1630
- *
1631
- * For examples and further specifications, refer to the
1632
- * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
1633
- */
1634
- class Timestamp {
1635
- /**
1636
- * Creates a new timestamp.
1637
- *
1638
- * @param seconds - The number of seconds of UTC time since Unix epoch
1639
- * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
1640
- * 9999-12-31T23:59:59Z inclusive.
1641
- * @param nanoseconds - The non-negative fractions of a second at nanosecond
1642
- * resolution. Negative second values with fractions must still have
1643
- * non-negative nanoseconds values that count forward in time. Must be
1644
- * from 0 to 999,999,999 inclusive.
1645
- */
1646
- constructor(
1647
- /**
1648
- * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
1649
- */
1650
- seconds,
1651
- /**
1652
- * The fractions of a second at nanosecond resolution.*
1653
- */
1654
- nanoseconds) {
1655
- this.seconds = seconds;
1656
- this.nanoseconds = nanoseconds;
1657
- if (nanoseconds < 0) {
1658
- throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds);
1659
- }
1660
- if (nanoseconds >= 1e9) {
1661
- throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds);
1662
- }
1663
- if (seconds < MIN_SECONDS) {
1664
- throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds);
1665
- }
1666
- // This will break in the year 10,000.
1667
- if (seconds >= 253402300800) {
1668
- throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds);
1616
+ function objectSize(obj) {
1617
+ let count = 0;
1618
+ for (const key in obj) {
1619
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
1620
+ count++;
1669
1621
  }
1670
1622
  }
1671
- /**
1672
- * Creates a new timestamp with the current date, with millisecond precision.
1673
- *
1674
- * @returns a new timestamp representing the current date.
1675
- */
1676
- static now() {
1677
- return Timestamp.fromMillis(Date.now());
1678
- }
1679
- /**
1680
- * Creates a new timestamp from the given date.
1681
- *
1682
- * @param date - The date to initialize the `Timestamp` from.
1683
- * @returns A new `Timestamp` representing the same point in time as the given
1684
- * date.
1685
- */
1686
- static fromDate(date) {
1687
- return Timestamp.fromMillis(date.getTime());
1688
- }
1689
- /**
1690
- * Creates a new timestamp from the given number of milliseconds.
1691
- *
1692
- * @param milliseconds - Number of milliseconds since Unix epoch
1693
- * 1970-01-01T00:00:00Z.
1694
- * @returns A new `Timestamp` representing the same point in time as the given
1695
- * number of milliseconds.
1696
- */
1697
- static fromMillis(milliseconds) {
1698
- const seconds = Math.floor(milliseconds / 1000);
1699
- const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);
1700
- return new Timestamp(seconds, nanos);
1701
- }
1702
- /**
1703
- * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
1704
- * causes a loss of precision since `Date` objects only support millisecond
1705
- * precision.
1706
- *
1707
- * @returns JavaScript `Date` object representing the same point in time as
1708
- * this `Timestamp`, with millisecond precision.
1709
- */
1710
- toDate() {
1711
- return new Date(this.toMillis());
1712
- }
1713
- /**
1714
- * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
1715
- * epoch). This operation causes a loss of precision.
1716
- *
1717
- * @returns The point in time corresponding to this timestamp, represented as
1718
- * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
1719
- */
1720
- toMillis() {
1721
- return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;
1722
- }
1723
- _compareTo(other) {
1724
- if (this.seconds === other.seconds) {
1725
- return primitiveComparator(this.nanoseconds, other.nanoseconds);
1623
+ return count;
1624
+ }
1625
+ function forEach(obj, fn) {
1626
+ for (const key in obj) {
1627
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
1628
+ fn(key, obj[key]);
1726
1629
  }
1727
- return primitiveComparator(this.seconds, other.seconds);
1728
- }
1729
- /**
1730
- * Returns true if this `Timestamp` is equal to the provided one.
1731
- *
1732
- * @param other - The `Timestamp` to compare against.
1733
- * @returns true if this `Timestamp` is equal to the provided one.
1734
- */
1735
- isEqual(other) {
1736
- return (other.seconds === this.seconds && other.nanoseconds === this.nanoseconds);
1737
- }
1738
- /** Returns a textual representation of this `Timestamp`. */
1739
- toString() {
1740
- return ('Timestamp(seconds=' +
1741
- this.seconds +
1742
- ', nanoseconds=' +
1743
- this.nanoseconds +
1744
- ')');
1745
- }
1746
- /** Returns a JSON-serializable representation of this `Timestamp`. */
1747
- toJSON() {
1748
- return { seconds: this.seconds, nanoseconds: this.nanoseconds };
1749
1630
  }
1750
- /**
1751
- * Converts this object to a primitive string, which allows `Timestamp` objects
1752
- * to be compared using the `>`, `<=`, `>=` and `>` operators.
1753
- */
1754
- valueOf() {
1755
- // This method returns a string of the form <seconds>.<nanoseconds> where
1756
- // <seconds> is translated to have a non-negative value and both <seconds>
1757
- // and <nanoseconds> are left-padded with zeroes to be a consistent length.
1758
- // Strings with this format then have a lexiographical ordering that matches
1759
- // the expected ordering. The <seconds> translation is done to avoid having
1760
- // a leading negative sign (i.e. a leading '-' character) in its string
1761
- // representation, which would affect its lexiographical ordering.
1762
- const adjustedSeconds = this.seconds - MIN_SECONDS;
1763
- // Note: Up to 12 decimal digits are required to represent all valid
1764
- // 'seconds' values.
1765
- const formattedSeconds = String(adjustedSeconds).padStart(12, '0');
1766
- const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');
1767
- return formattedSeconds + '.' + formattedNanoseconds;
1631
+ }
1632
+ function isEmpty(obj) {
1633
+ for (const key in obj) {
1634
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
1635
+ return false;
1636
+ }
1768
1637
  }
1638
+ return true;
1769
1639
  }
1770
1640
 
1771
1641
  /**
@@ -1785,44 +1655,32 @@ class Timestamp {
1785
1655
  * limitations under the License.
1786
1656
  */
1787
1657
  /**
1788
- * A version of a document in Firestore. This corresponds to the version
1789
- * timestamp, such as update_time or read_time.
1658
+ * Returns whether a variable is either undefined or null.
1790
1659
  */
1791
- class SnapshotVersion {
1792
- constructor(timestamp) {
1793
- this.timestamp = timestamp;
1794
- }
1795
- static fromTimestamp(value) {
1796
- return new SnapshotVersion(value);
1797
- }
1798
- static min() {
1799
- return new SnapshotVersion(new Timestamp(0, 0));
1800
- }
1801
- static max() {
1802
- return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));
1803
- }
1804
- compareTo(other) {
1805
- return this.timestamp._compareTo(other.timestamp);
1806
- }
1807
- isEqual(other) {
1808
- return this.timestamp.isEqual(other.timestamp);
1809
- }
1810
- /** Returns a number representation of the version for use in spec tests. */
1811
- toMicroseconds() {
1812
- // Convert to microseconds.
1813
- return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;
1814
- }
1815
- toString() {
1816
- return 'SnapshotVersion(' + this.timestamp.toString() + ')';
1817
- }
1818
- toTimestamp() {
1819
- return this.timestamp;
1820
- }
1660
+ function isNullOrUndefined(value) {
1661
+ return value === null || value === undefined;
1662
+ }
1663
+ /** Returns whether the value represents -0. */
1664
+ function isNegativeZero(value) {
1665
+ // Detect if the value is -0.0. Based on polyfill from
1666
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
1667
+ return value === 0 && 1 / value === 1 / -0;
1668
+ }
1669
+ /**
1670
+ * Returns whether a value is an integer and in the safe integer range
1671
+ * @param value - The value to test for being an integer and in the safe range
1672
+ */
1673
+ function isSafeInteger(value) {
1674
+ return (typeof value === 'number' &&
1675
+ Number.isInteger(value) &&
1676
+ !isNegativeZero(value) &&
1677
+ value <= Number.MAX_SAFE_INTEGER &&
1678
+ value >= Number.MIN_SAFE_INTEGER);
1821
1679
  }
1822
1680
 
1823
1681
  /**
1824
1682
  * @license
1825
- * Copyright 2017 Google LLC
1683
+ * Copyright 2020 Google LLC
1826
1684
  *
1827
1685
  * Licensed under the Apache License, Version 2.0 (the "License");
1828
1686
  * you may not use this file except in compliance with the License.
@@ -1836,34 +1694,20 @@ class SnapshotVersion {
1836
1694
  * See the License for the specific language governing permissions and
1837
1695
  * limitations under the License.
1838
1696
  */
1839
- function objectSize(obj) {
1840
- let count = 0;
1841
- for (const key in obj) {
1842
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
1843
- count++;
1844
- }
1845
- }
1846
- return count;
1847
- }
1848
- function forEach(obj, fn) {
1849
- for (const key in obj) {
1850
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
1851
- fn(key, obj[key]);
1852
- }
1853
- }
1697
+ /** Converts a Base64 encoded string to a binary string. */
1698
+ function decodeBase64(encoded) {
1699
+ // Note: We used to validate the base64 string here via a regular expression.
1700
+ // This was removed to improve the performance of indexing.
1701
+ return Buffer.from(encoded, 'base64').toString('binary');
1854
1702
  }
1855
- function isEmpty(obj) {
1856
- for (const key in obj) {
1857
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
1858
- return false;
1859
- }
1860
- }
1861
- return true;
1703
+ /** Converts a binary string to a Base64 encoded string. */
1704
+ function encodeBase64(raw) {
1705
+ return Buffer.from(raw, 'binary').toString('base64');
1862
1706
  }
1863
1707
 
1864
1708
  /**
1865
1709
  * @license
1866
- * Copyright 2017 Google LLC
1710
+ * Copyright 2020 Google LLC
1867
1711
  *
1868
1712
  * Licensed under the Apache License, Version 2.0 (the "License");
1869
1713
  * you may not use this file except in compliance with the License.
@@ -1877,449 +1721,334 @@ function isEmpty(obj) {
1877
1721
  * See the License for the specific language governing permissions and
1878
1722
  * limitations under the License.
1879
1723
  */
1880
- // An immutable sorted map implementation, based on a Left-leaning Red-Black
1881
- // tree.
1882
- class SortedMap {
1883
- constructor(comparator, root) {
1884
- this.comparator = comparator;
1885
- this.root = root ? root : LLRBNode.EMPTY;
1724
+ /**
1725
+ * Immutable class that represents a "proto" byte string.
1726
+ *
1727
+ * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
1728
+ * sent on the wire. This class abstracts away this differentiation by holding
1729
+ * the proto byte string in a common class that must be converted into a string
1730
+ * before being sent as a proto.
1731
+ * @internal
1732
+ */
1733
+ class ByteString {
1734
+ constructor(binaryString) {
1735
+ this.binaryString = binaryString;
1886
1736
  }
1887
- // Returns a copy of the map, with the specified key/value added or replaced.
1888
- insert(key, value) {
1889
- return new SortedMap(this.comparator, this.root
1890
- .insert(key, value, this.comparator)
1891
- .copy(null, null, LLRBNode.BLACK, null, null));
1737
+ static fromBase64String(base64) {
1738
+ const binaryString = decodeBase64(base64);
1739
+ return new ByteString(binaryString);
1892
1740
  }
1893
- // Returns a copy of the map, with the specified key removed.
1894
- remove(key) {
1895
- return new SortedMap(this.comparator, this.root
1896
- .remove(key, this.comparator)
1897
- .copy(null, null, LLRBNode.BLACK, null, null));
1741
+ static fromUint8Array(array) {
1742
+ // TODO(indexing); Remove the copy of the byte string here as this method
1743
+ // is frequently called during indexing.
1744
+ const binaryString = binaryStringFromUint8Array(array);
1745
+ return new ByteString(binaryString);
1898
1746
  }
1899
- // Returns the value of the node with the given key, or null.
1900
- get(key) {
1901
- let node = this.root;
1902
- while (!node.isEmpty()) {
1903
- const cmp = this.comparator(key, node.key);
1904
- if (cmp === 0) {
1905
- return node.value;
1906
- }
1907
- else if (cmp < 0) {
1908
- node = node.left;
1909
- }
1910
- else if (cmp > 0) {
1911
- node = node.right;
1747
+ [Symbol.iterator]() {
1748
+ let i = 0;
1749
+ return {
1750
+ next: () => {
1751
+ if (i < this.binaryString.length) {
1752
+ return { value: this.binaryString.charCodeAt(i++), done: false };
1753
+ }
1754
+ else {
1755
+ return { value: undefined, done: true };
1756
+ }
1912
1757
  }
1913
- }
1914
- return null;
1758
+ };
1915
1759
  }
1916
- // Returns the index of the element in this sorted map, or -1 if it doesn't
1917
- // exist.
1918
- indexOf(key) {
1919
- // Number of nodes that were pruned when descending right
1920
- let prunedNodes = 0;
1921
- let node = this.root;
1922
- while (!node.isEmpty()) {
1923
- const cmp = this.comparator(key, node.key);
1924
- if (cmp === 0) {
1925
- return prunedNodes + node.left.size;
1926
- }
1927
- else if (cmp < 0) {
1928
- node = node.left;
1929
- }
1930
- else {
1931
- // Count all nodes left of the node plus the node itself
1932
- prunedNodes += node.left.size + 1;
1933
- node = node.right;
1934
- }
1935
- }
1936
- // Node not found
1937
- return -1;
1760
+ toBase64() {
1761
+ return encodeBase64(this.binaryString);
1938
1762
  }
1939
- isEmpty() {
1940
- return this.root.isEmpty();
1763
+ toUint8Array() {
1764
+ return uint8ArrayFromBinaryString(this.binaryString);
1941
1765
  }
1942
- // Returns the total number of nodes in the map.
1943
- get size() {
1944
- return this.root.size;
1766
+ approximateByteSize() {
1767
+ return this.binaryString.length * 2;
1945
1768
  }
1946
- // Returns the minimum key in the map.
1947
- minKey() {
1948
- return this.root.minKey();
1769
+ compareTo(other) {
1770
+ return primitiveComparator(this.binaryString, other.binaryString);
1949
1771
  }
1950
- // Returns the maximum key in the map.
1951
- maxKey() {
1952
- return this.root.maxKey();
1772
+ isEqual(other) {
1773
+ return this.binaryString === other.binaryString;
1953
1774
  }
1954
- // Traverses the map in key order and calls the specified action function
1955
- // for each key/value pair. If action returns true, traversal is aborted.
1956
- // Returns the first truthy value returned by action, or the last falsey
1957
- // value returned by action.
1958
- inorderTraversal(action) {
1959
- return this.root.inorderTraversal(action);
1775
+ }
1776
+ ByteString.EMPTY_BYTE_STRING = new ByteString('');
1777
+ /**
1778
+ * Helper function to convert an Uint8array to a binary string.
1779
+ */
1780
+ function binaryStringFromUint8Array(array) {
1781
+ let binaryString = '';
1782
+ for (let i = 0; i < array.length; ++i) {
1783
+ binaryString += String.fromCharCode(array[i]);
1960
1784
  }
1961
- forEach(fn) {
1962
- this.inorderTraversal((k, v) => {
1963
- fn(k, v);
1964
- return false;
1965
- });
1785
+ return binaryString;
1786
+ }
1787
+ /**
1788
+ * Helper function to convert a binary string to an Uint8Array.
1789
+ */
1790
+ function uint8ArrayFromBinaryString(binaryString) {
1791
+ const buffer = new Uint8Array(binaryString.length);
1792
+ for (let i = 0; i < binaryString.length; i++) {
1793
+ buffer[i] = binaryString.charCodeAt(i);
1966
1794
  }
1967
- toString() {
1968
- const descriptions = [];
1969
- this.inorderTraversal((k, v) => {
1970
- descriptions.push(`${k}:${v}`);
1971
- return false;
1972
- });
1973
- return `{${descriptions.join(', ')}}`;
1795
+ return buffer;
1796
+ }
1797
+
1798
+ /**
1799
+ * @license
1800
+ * Copyright 2020 Google LLC
1801
+ *
1802
+ * Licensed under the Apache License, Version 2.0 (the "License");
1803
+ * you may not use this file except in compliance with the License.
1804
+ * You may obtain a copy of the License at
1805
+ *
1806
+ * http://www.apache.org/licenses/LICENSE-2.0
1807
+ *
1808
+ * Unless required by applicable law or agreed to in writing, software
1809
+ * distributed under the License is distributed on an "AS IS" BASIS,
1810
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1811
+ * See the License for the specific language governing permissions and
1812
+ * limitations under the License.
1813
+ */
1814
+ // A RegExp matching ISO 8601 UTC timestamps with optional fraction.
1815
+ const ISO_TIMESTAMP_REG_EXP = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
1816
+ /**
1817
+ * Converts the possible Proto values for a timestamp value into a "seconds and
1818
+ * nanos" representation.
1819
+ */
1820
+ function normalizeTimestamp(date) {
1821
+ hardAssert(!!date);
1822
+ // The json interface (for the browser) will return an iso timestamp string,
1823
+ // while the proto js library (for node) will return a
1824
+ // google.protobuf.Timestamp instance.
1825
+ if (typeof date === 'string') {
1826
+ // The date string can have higher precision (nanos) than the Date class
1827
+ // (millis), so we do some custom parsing here.
1828
+ // Parse the nanos right out of the string.
1829
+ let nanos = 0;
1830
+ const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);
1831
+ hardAssert(!!fraction);
1832
+ if (fraction[1]) {
1833
+ // Pad the fraction out to 9 digits (nanos).
1834
+ let nanoStr = fraction[1];
1835
+ nanoStr = (nanoStr + '000000000').substr(0, 9);
1836
+ nanos = Number(nanoStr);
1837
+ }
1838
+ // Parse the date to get the seconds.
1839
+ const parsedDate = new Date(date);
1840
+ const seconds = Math.floor(parsedDate.getTime() / 1000);
1841
+ return { seconds, nanos };
1974
1842
  }
1975
- // Traverses the map in reverse key order and calls the specified action
1976
- // function for each key/value pair. If action returns true, traversal is
1977
- // aborted.
1978
- // Returns the first truthy value returned by action, or the last falsey
1979
- // value returned by action.
1980
- reverseTraversal(action) {
1981
- return this.root.reverseTraversal(action);
1843
+ else {
1844
+ // TODO(b/37282237): Use strings for Proto3 timestamps
1845
+ // assert(!this.options.useProto3Json,
1846
+ // 'The timestamp instance format requires Proto JS.');
1847
+ const seconds = normalizeNumber(date.seconds);
1848
+ const nanos = normalizeNumber(date.nanos);
1849
+ return { seconds, nanos };
1982
1850
  }
1983
- // Returns an iterator over the SortedMap.
1984
- getIterator() {
1985
- return new SortedMapIterator(this.root, null, this.comparator, false);
1851
+ }
1852
+ /**
1853
+ * Converts the possible Proto types for numbers into a JavaScript number.
1854
+ * Returns 0 if the value is not numeric.
1855
+ */
1856
+ function normalizeNumber(value) {
1857
+ // TODO(bjornick): Handle int64 greater than 53 bits.
1858
+ if (typeof value === 'number') {
1859
+ return value;
1986
1860
  }
1987
- getIteratorFrom(key) {
1988
- return new SortedMapIterator(this.root, key, this.comparator, false);
1861
+ else if (typeof value === 'string') {
1862
+ return Number(value);
1989
1863
  }
1990
- getReverseIterator() {
1991
- return new SortedMapIterator(this.root, null, this.comparator, true);
1864
+ else {
1865
+ return 0;
1992
1866
  }
1993
- getReverseIteratorFrom(key) {
1994
- return new SortedMapIterator(this.root, key, this.comparator, true);
1867
+ }
1868
+ /** Converts the possible Proto types for Blobs into a ByteString. */
1869
+ function normalizeByteString(blob) {
1870
+ if (typeof blob === 'string') {
1871
+ return ByteString.fromBase64String(blob);
1995
1872
  }
1996
- } // end SortedMap
1997
- // An iterator over an LLRBNode.
1998
- class SortedMapIterator {
1999
- constructor(node, startKey, comparator, isReverse) {
2000
- this.isReverse = isReverse;
2001
- this.nodeStack = [];
2002
- let cmp = 1;
2003
- while (!node.isEmpty()) {
2004
- cmp = startKey ? comparator(node.key, startKey) : 1;
2005
- // flip the comparison if we're going in reverse
2006
- if (startKey && isReverse) {
2007
- cmp *= -1;
2008
- }
2009
- if (cmp < 0) {
2010
- // This node is less than our start key. ignore it
2011
- if (this.isReverse) {
2012
- node = node.left;
2013
- }
2014
- else {
2015
- node = node.right;
2016
- }
2017
- }
2018
- else if (cmp === 0) {
2019
- // This node is exactly equal to our start key. Push it on the stack,
2020
- // but stop iterating;
2021
- this.nodeStack.push(node);
2022
- break;
2023
- }
2024
- else {
2025
- // This node is greater than our start key, add it to the stack and move
2026
- // to the next one
2027
- this.nodeStack.push(node);
2028
- if (this.isReverse) {
2029
- node = node.right;
2030
- }
2031
- else {
2032
- node = node.left;
2033
- }
2034
- }
2035
- }
1873
+ else {
1874
+ return ByteString.fromUint8Array(blob);
2036
1875
  }
2037
- getNext() {
2038
- let node = this.nodeStack.pop();
2039
- const result = { key: node.key, value: node.value };
2040
- if (this.isReverse) {
2041
- node = node.left;
2042
- while (!node.isEmpty()) {
2043
- this.nodeStack.push(node);
2044
- node = node.right;
2045
- }
1876
+ }
1877
+
1878
+ /**
1879
+ * @license
1880
+ * Copyright 2017 Google LLC
1881
+ *
1882
+ * Licensed under the Apache License, Version 2.0 (the "License");
1883
+ * you may not use this file except in compliance with the License.
1884
+ * You may obtain a copy of the License at
1885
+ *
1886
+ * http://www.apache.org/licenses/LICENSE-2.0
1887
+ *
1888
+ * Unless required by applicable law or agreed to in writing, software
1889
+ * distributed under the License is distributed on an "AS IS" BASIS,
1890
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1891
+ * See the License for the specific language governing permissions and
1892
+ * limitations under the License.
1893
+ */
1894
+ // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
1895
+ const MIN_SECONDS = -62135596800;
1896
+ // Number of nanoseconds in a millisecond.
1897
+ const MS_TO_NANOS = 1e6;
1898
+ /**
1899
+ * A `Timestamp` represents a point in time independent of any time zone or
1900
+ * calendar, represented as seconds and fractions of seconds at nanosecond
1901
+ * resolution in UTC Epoch time.
1902
+ *
1903
+ * It is encoded using the Proleptic Gregorian Calendar which extends the
1904
+ * Gregorian calendar backwards to year one. It is encoded assuming all minutes
1905
+ * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
1906
+ * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
1907
+ * 9999-12-31T23:59:59.999999999Z.
1908
+ *
1909
+ * For examples and further specifications, refer to the
1910
+ * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
1911
+ */
1912
+ class Timestamp {
1913
+ /**
1914
+ * Creates a new timestamp.
1915
+ *
1916
+ * @param seconds - The number of seconds of UTC time since Unix epoch
1917
+ * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
1918
+ * 9999-12-31T23:59:59Z inclusive.
1919
+ * @param nanoseconds - The non-negative fractions of a second at nanosecond
1920
+ * resolution. Negative second values with fractions must still have
1921
+ * non-negative nanoseconds values that count forward in time. Must be
1922
+ * from 0 to 999,999,999 inclusive.
1923
+ */
1924
+ constructor(
1925
+ /**
1926
+ * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
1927
+ */
1928
+ seconds,
1929
+ /**
1930
+ * The fractions of a second at nanosecond resolution.*
1931
+ */
1932
+ nanoseconds) {
1933
+ this.seconds = seconds;
1934
+ this.nanoseconds = nanoseconds;
1935
+ if (nanoseconds < 0) {
1936
+ throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds);
2046
1937
  }
2047
- else {
2048
- node = node.right;
2049
- while (!node.isEmpty()) {
2050
- this.nodeStack.push(node);
2051
- node = node.left;
2052
- }
1938
+ if (nanoseconds >= 1e9) {
1939
+ throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds);
2053
1940
  }
2054
- return result;
2055
- }
2056
- hasNext() {
2057
- return this.nodeStack.length > 0;
2058
- }
2059
- peek() {
2060
- if (this.nodeStack.length === 0) {
2061
- return null;
1941
+ if (seconds < MIN_SECONDS) {
1942
+ throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds);
1943
+ }
1944
+ // This will break in the year 10,000.
1945
+ if (seconds >= 253402300800) {
1946
+ throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds);
2062
1947
  }
2063
- const node = this.nodeStack[this.nodeStack.length - 1];
2064
- return { key: node.key, value: node.value };
2065
1948
  }
2066
- } // end SortedMapIterator
2067
- // Represents a node in a Left-leaning Red-Black tree.
2068
- class LLRBNode {
2069
- constructor(key, value, color, left, right) {
2070
- this.key = key;
2071
- this.value = value;
2072
- this.color = color != null ? color : LLRBNode.RED;
2073
- this.left = left != null ? left : LLRBNode.EMPTY;
2074
- this.right = right != null ? right : LLRBNode.EMPTY;
2075
- this.size = this.left.size + 1 + this.right.size;
1949
+ /**
1950
+ * Creates a new timestamp with the current date, with millisecond precision.
1951
+ *
1952
+ * @returns a new timestamp representing the current date.
1953
+ */
1954
+ static now() {
1955
+ return Timestamp.fromMillis(Date.now());
2076
1956
  }
2077
- // Returns a copy of the current node, optionally replacing pieces of it.
2078
- copy(key, value, color, left, right) {
2079
- return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
1957
+ /**
1958
+ * Creates a new timestamp from the given date.
1959
+ *
1960
+ * @param date - The date to initialize the `Timestamp` from.
1961
+ * @returns A new `Timestamp` representing the same point in time as the given
1962
+ * date.
1963
+ */
1964
+ static fromDate(date) {
1965
+ return Timestamp.fromMillis(date.getTime());
2080
1966
  }
2081
- isEmpty() {
2082
- return false;
1967
+ /**
1968
+ * Creates a new timestamp from the given number of milliseconds.
1969
+ *
1970
+ * @param milliseconds - Number of milliseconds since Unix epoch
1971
+ * 1970-01-01T00:00:00Z.
1972
+ * @returns A new `Timestamp` representing the same point in time as the given
1973
+ * number of milliseconds.
1974
+ */
1975
+ static fromMillis(milliseconds) {
1976
+ const seconds = Math.floor(milliseconds / 1000);
1977
+ const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS);
1978
+ return new Timestamp(seconds, nanos);
2083
1979
  }
2084
- // Traverses the tree in key order and calls the specified action function
2085
- // for each node. If action returns true, traversal is aborted.
2086
- // Returns the first truthy value returned by action, or the last falsey
2087
- // value returned by action.
2088
- inorderTraversal(action) {
2089
- return (this.left.inorderTraversal(action) ||
2090
- action(this.key, this.value) ||
2091
- this.right.inorderTraversal(action));
1980
+ /**
1981
+ * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
1982
+ * causes a loss of precision since `Date` objects only support millisecond
1983
+ * precision.
1984
+ *
1985
+ * @returns JavaScript `Date` object representing the same point in time as
1986
+ * this `Timestamp`, with millisecond precision.
1987
+ */
1988
+ toDate() {
1989
+ return new Date(this.toMillis());
2092
1990
  }
2093
- // Traverses the tree in reverse key order and calls the specified action
2094
- // function for each node. If action returns true, traversal is aborted.
2095
- // Returns the first truthy value returned by action, or the last falsey
2096
- // value returned by action.
2097
- reverseTraversal(action) {
2098
- return (this.right.reverseTraversal(action) ||
2099
- action(this.key, this.value) ||
2100
- this.left.reverseTraversal(action));
1991
+ /**
1992
+ * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
1993
+ * epoch). This operation causes a loss of precision.
1994
+ *
1995
+ * @returns The point in time corresponding to this timestamp, represented as
1996
+ * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
1997
+ */
1998
+ toMillis() {
1999
+ return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS;
2101
2000
  }
2102
- // Returns the minimum node in the tree.
2103
- min() {
2104
- if (this.left.isEmpty()) {
2105
- return this;
2106
- }
2107
- else {
2108
- return this.left.min();
2001
+ _compareTo(other) {
2002
+ if (this.seconds === other.seconds) {
2003
+ return primitiveComparator(this.nanoseconds, other.nanoseconds);
2109
2004
  }
2005
+ return primitiveComparator(this.seconds, other.seconds);
2110
2006
  }
2111
- // Returns the maximum key in the tree.
2112
- minKey() {
2113
- return this.min().key;
2114
- }
2115
- // Returns the maximum key in the tree.
2116
- maxKey() {
2117
- if (this.right.isEmpty()) {
2118
- return this.key;
2119
- }
2120
- else {
2121
- return this.right.maxKey();
2122
- }
2007
+ /**
2008
+ * Returns true if this `Timestamp` is equal to the provided one.
2009
+ *
2010
+ * @param other - The `Timestamp` to compare against.
2011
+ * @returns true if this `Timestamp` is equal to the provided one.
2012
+ */
2013
+ isEqual(other) {
2014
+ return (other.seconds === this.seconds && other.nanoseconds === this.nanoseconds);
2123
2015
  }
2124
- // Returns new tree, with the key/value added.
2125
- insert(key, value, comparator) {
2126
- let n = this;
2127
- const cmp = comparator(key, n.key);
2128
- if (cmp < 0) {
2129
- n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
2130
- }
2131
- else if (cmp === 0) {
2132
- n = n.copy(null, value, null, null, null);
2133
- }
2134
- else {
2135
- n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
2136
- }
2137
- return n.fixUp();
2016
+ /** Returns a textual representation of this `Timestamp`. */
2017
+ toString() {
2018
+ return ('Timestamp(seconds=' +
2019
+ this.seconds +
2020
+ ', nanoseconds=' +
2021
+ this.nanoseconds +
2022
+ ')');
2138
2023
  }
2139
- removeMin() {
2140
- if (this.left.isEmpty()) {
2141
- return LLRBNode.EMPTY;
2142
- }
2143
- let n = this;
2144
- if (!n.left.isRed() && !n.left.left.isRed()) {
2145
- n = n.moveRedLeft();
2146
- }
2147
- n = n.copy(null, null, null, n.left.removeMin(), null);
2148
- return n.fixUp();
2024
+ /** Returns a JSON-serializable representation of this `Timestamp`. */
2025
+ toJSON() {
2026
+ return { seconds: this.seconds, nanoseconds: this.nanoseconds };
2149
2027
  }
2150
- // Returns new tree, with the specified item removed.
2151
- remove(key, comparator) {
2152
- let smallest;
2153
- let n = this;
2154
- if (comparator(key, n.key) < 0) {
2155
- if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {
2156
- n = n.moveRedLeft();
2157
- }
2158
- n = n.copy(null, null, null, n.left.remove(key, comparator), null);
2159
- }
2160
- else {
2161
- if (n.left.isRed()) {
2162
- n = n.rotateRight();
2163
- }
2164
- if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {
2165
- n = n.moveRedRight();
2166
- }
2167
- if (comparator(key, n.key) === 0) {
2168
- if (n.right.isEmpty()) {
2169
- return LLRBNode.EMPTY;
2170
- }
2171
- else {
2172
- smallest = n.right.min();
2173
- n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());
2174
- }
2175
- }
2176
- n = n.copy(null, null, null, null, n.right.remove(key, comparator));
2177
- }
2178
- return n.fixUp();
2179
- }
2180
- isRed() {
2181
- return this.color;
2182
- }
2183
- // Returns new tree after performing any needed rotations.
2184
- fixUp() {
2185
- let n = this;
2186
- if (n.right.isRed() && !n.left.isRed()) {
2187
- n = n.rotateLeft();
2188
- }
2189
- if (n.left.isRed() && n.left.left.isRed()) {
2190
- n = n.rotateRight();
2191
- }
2192
- if (n.left.isRed() && n.right.isRed()) {
2193
- n = n.colorFlip();
2194
- }
2195
- return n;
2196
- }
2197
- moveRedLeft() {
2198
- let n = this.colorFlip();
2199
- if (n.right.left.isRed()) {
2200
- n = n.copy(null, null, null, null, n.right.rotateRight());
2201
- n = n.rotateLeft();
2202
- n = n.colorFlip();
2203
- }
2204
- return n;
2205
- }
2206
- moveRedRight() {
2207
- let n = this.colorFlip();
2208
- if (n.left.left.isRed()) {
2209
- n = n.rotateRight();
2210
- n = n.colorFlip();
2211
- }
2212
- return n;
2213
- }
2214
- rotateLeft() {
2215
- const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
2216
- return this.right.copy(null, null, this.color, nl, null);
2217
- }
2218
- rotateRight() {
2219
- const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
2220
- return this.left.copy(null, null, this.color, null, nr);
2221
- }
2222
- colorFlip() {
2223
- const left = this.left.copy(null, null, !this.left.color, null, null);
2224
- const right = this.right.copy(null, null, !this.right.color, null, null);
2225
- return this.copy(null, null, !this.color, left, right);
2226
- }
2227
- // For testing.
2228
- checkMaxDepth() {
2229
- const blackDepth = this.check();
2230
- if (Math.pow(2.0, blackDepth) <= this.size + 1) {
2231
- return true;
2232
- }
2233
- else {
2234
- return false;
2235
- }
2236
- }
2237
- // In a balanced RB tree, the black-depth (number of black nodes) from root to
2238
- // leaves is equal on both sides. This function verifies that or asserts.
2239
- check() {
2240
- if (this.isRed() && this.left.isRed()) {
2241
- throw fail();
2242
- }
2243
- if (this.right.isRed()) {
2244
- throw fail();
2245
- }
2246
- const blackDepth = this.left.check();
2247
- if (blackDepth !== this.right.check()) {
2248
- throw fail();
2249
- }
2250
- else {
2251
- return blackDepth + (this.isRed() ? 0 : 1);
2252
- }
2253
- }
2254
- } // end LLRBNode
2255
- // Empty node is shared between all LLRB trees.
2256
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2257
- LLRBNode.EMPTY = null;
2258
- LLRBNode.RED = true;
2259
- LLRBNode.BLACK = false;
2260
- // Represents an empty node (a leaf node in the Red-Black Tree).
2261
- class LLRBEmptyNode {
2262
- constructor() {
2263
- this.size = 0;
2264
- }
2265
- get key() {
2266
- throw fail();
2267
- }
2268
- get value() {
2269
- throw fail();
2270
- }
2271
- get color() {
2272
- throw fail();
2273
- }
2274
- get left() {
2275
- throw fail();
2276
- }
2277
- get right() {
2278
- throw fail();
2279
- }
2280
- // Returns a copy of the current node.
2281
- copy(key, value, color, left, right) {
2282
- return this;
2283
- }
2284
- // Returns a copy of the tree, with the specified key/value added.
2285
- insert(key, value, comparator) {
2286
- return new LLRBNode(key, value);
2287
- }
2288
- // Returns a copy of the tree, with the specified key removed.
2289
- remove(key, comparator) {
2290
- return this;
2291
- }
2292
- isEmpty() {
2293
- return true;
2294
- }
2295
- inorderTraversal(action) {
2296
- return false;
2297
- }
2298
- reverseTraversal(action) {
2299
- return false;
2300
- }
2301
- minKey() {
2302
- return null;
2303
- }
2304
- maxKey() {
2305
- return null;
2306
- }
2307
- isRed() {
2308
- return false;
2309
- }
2310
- // For testing.
2311
- checkMaxDepth() {
2312
- return true;
2313
- }
2314
- check() {
2315
- return 0;
2028
+ /**
2029
+ * Converts this object to a primitive string, which allows `Timestamp` objects
2030
+ * to be compared using the `>`, `<=`, `>=` and `>` operators.
2031
+ */
2032
+ valueOf() {
2033
+ // This method returns a string of the form <seconds>.<nanoseconds> where
2034
+ // <seconds> is translated to have a non-negative value and both <seconds>
2035
+ // and <nanoseconds> are left-padded with zeroes to be a consistent length.
2036
+ // Strings with this format then have a lexiographical ordering that matches
2037
+ // the expected ordering. The <seconds> translation is done to avoid having
2038
+ // a leading negative sign (i.e. a leading '-' character) in its string
2039
+ // representation, which would affect its lexiographical ordering.
2040
+ const adjustedSeconds = this.seconds - MIN_SECONDS;
2041
+ // Note: Up to 12 decimal digits are required to represent all valid
2042
+ // 'seconds' values.
2043
+ const formattedSeconds = String(adjustedSeconds).padStart(12, '0');
2044
+ const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');
2045
+ return formattedSeconds + '.' + formattedNanoseconds;
2316
2046
  }
2317
- } // end LLRBEmptyNode
2318
- LLRBNode.EMPTY = new LLRBEmptyNode();
2047
+ }
2319
2048
 
2320
2049
  /**
2321
2050
  * @license
2322
- * Copyright 2017 Google LLC
2051
+ * Copyright 2020 Google LLC
2323
2052
  *
2324
2053
  * Licensed under the Apache License, Version 2.0 (the "License");
2325
2054
  * you may not use this file except in compliance with the License.
@@ -2334,152 +2063,51 @@ LLRBNode.EMPTY = new LLRBEmptyNode();
2334
2063
  * limitations under the License.
2335
2064
  */
2336
2065
  /**
2337
- * SortedSet is an immutable (copy-on-write) collection that holds elements
2338
- * in order specified by the provided comparator.
2066
+ * Represents a locally-applied ServerTimestamp.
2339
2067
  *
2340
- * NOTE: if provided comparator returns 0 for two elements, we consider them to
2341
- * be equal!
2068
+ * Server Timestamps are backed by MapValues that contain an internal field
2069
+ * `__type__` with a value of `server_timestamp`. The previous value and local
2070
+ * write time are stored in its `__previous_value__` and `__local_write_time__`
2071
+ * fields respectively.
2072
+ *
2073
+ * Notes:
2074
+ * - ServerTimestampValue instances are created as the result of applying a
2075
+ * transform. They can only exist in the local view of a document. Therefore
2076
+ * they do not need to be parsed or serialized.
2077
+ * - When evaluated locally (e.g. for snapshot.data()), they by default
2078
+ * evaluate to `null`. This behavior can be configured by passing custom
2079
+ * FieldValueOptions to value().
2080
+ * - With respect to other ServerTimestampValues, they sort by their
2081
+ * localWriteTime.
2342
2082
  */
2343
- class SortedSet {
2344
- constructor(comparator) {
2345
- this.comparator = comparator;
2346
- this.data = new SortedMap(this.comparator);
2347
- }
2348
- has(elem) {
2349
- return this.data.get(elem) !== null;
2350
- }
2351
- first() {
2352
- return this.data.minKey();
2353
- }
2354
- last() {
2355
- return this.data.maxKey();
2356
- }
2357
- get size() {
2358
- return this.data.size;
2359
- }
2360
- indexOf(elem) {
2361
- return this.data.indexOf(elem);
2362
- }
2363
- /** Iterates elements in order defined by "comparator" */
2364
- forEach(cb) {
2365
- this.data.inorderTraversal((k, v) => {
2366
- cb(k);
2367
- return false;
2368
- });
2369
- }
2370
- /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
2371
- forEachInRange(range, cb) {
2372
- const iter = this.data.getIteratorFrom(range[0]);
2373
- while (iter.hasNext()) {
2374
- const elem = iter.getNext();
2375
- if (this.comparator(elem.key, range[1]) >= 0) {
2376
- return;
2377
- }
2378
- cb(elem.key);
2379
- }
2380
- }
2381
- /**
2382
- * Iterates over `elem`s such that: start &lt;= elem until false is returned.
2383
- */
2384
- forEachWhile(cb, start) {
2385
- let iter;
2386
- if (start !== undefined) {
2387
- iter = this.data.getIteratorFrom(start);
2388
- }
2389
- else {
2390
- iter = this.data.getIterator();
2391
- }
2392
- while (iter.hasNext()) {
2393
- const elem = iter.getNext();
2394
- const result = cb(elem.key);
2395
- if (!result) {
2396
- return;
2397
- }
2398
- }
2399
- }
2400
- /** Finds the least element greater than or equal to `elem`. */
2401
- firstAfterOrEqual(elem) {
2402
- const iter = this.data.getIteratorFrom(elem);
2403
- return iter.hasNext() ? iter.getNext().key : null;
2404
- }
2405
- getIterator() {
2406
- return new SortedSetIterator(this.data.getIterator());
2407
- }
2408
- getIteratorFrom(key) {
2409
- return new SortedSetIterator(this.data.getIteratorFrom(key));
2410
- }
2411
- /** Inserts or updates an element */
2412
- add(elem) {
2413
- return this.copy(this.data.remove(elem).insert(elem, true));
2414
- }
2415
- /** Deletes an element */
2416
- delete(elem) {
2417
- if (!this.has(elem)) {
2418
- return this;
2419
- }
2420
- return this.copy(this.data.remove(elem));
2421
- }
2422
- isEmpty() {
2423
- return this.data.isEmpty();
2424
- }
2425
- unionWith(other) {
2426
- let result = this;
2427
- // Make sure `result` always refers to the larger one of the two sets.
2428
- if (result.size < other.size) {
2429
- result = other;
2430
- other = this;
2431
- }
2432
- other.forEach(elem => {
2433
- result = result.add(elem);
2434
- });
2435
- return result;
2436
- }
2437
- isEqual(other) {
2438
- if (!(other instanceof SortedSet)) {
2439
- return false;
2440
- }
2441
- if (this.size !== other.size) {
2442
- return false;
2443
- }
2444
- const thisIt = this.data.getIterator();
2445
- const otherIt = other.data.getIterator();
2446
- while (thisIt.hasNext()) {
2447
- const thisElem = thisIt.getNext().key;
2448
- const otherElem = otherIt.getNext().key;
2449
- if (this.comparator(thisElem, otherElem) !== 0) {
2450
- return false;
2451
- }
2452
- }
2453
- return true;
2454
- }
2455
- toArray() {
2456
- const res = [];
2457
- this.forEach(targetId => {
2458
- res.push(targetId);
2459
- });
2460
- return res;
2461
- }
2462
- toString() {
2463
- const result = [];
2464
- this.forEach(elem => result.push(elem));
2465
- return 'SortedSet(' + result.toString() + ')';
2466
- }
2467
- copy(data) {
2468
- const result = new SortedSet(this.comparator);
2469
- result.data = data;
2470
- return result;
2083
+ const SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';
2084
+ const TYPE_KEY = '__type__';
2085
+ const PREVIOUS_VALUE_KEY = '__previous_value__';
2086
+ const LOCAL_WRITE_TIME_KEY = '__local_write_time__';
2087
+ function isServerTimestamp(value) {
2088
+ var _a, _b;
2089
+ const type = (_b = (((_a = value === null || value === void 0 ? void 0 : value.mapValue) === null || _a === void 0 ? void 0 : _a.fields) || {})[TYPE_KEY]) === null || _b === void 0 ? void 0 : _b.stringValue;
2090
+ return type === SERVER_TIMESTAMP_SENTINEL;
2091
+ }
2092
+ /**
2093
+ * Returns the value of the field before this ServerTimestamp was set.
2094
+ *
2095
+ * Preserving the previous values allows the user to display the last resoled
2096
+ * value until the backend responds with the timestamp.
2097
+ */
2098
+ function getPreviousValue(value) {
2099
+ const previousValue = value.mapValue.fields[PREVIOUS_VALUE_KEY];
2100
+ if (isServerTimestamp(previousValue)) {
2101
+ return getPreviousValue(previousValue);
2471
2102
  }
2103
+ return previousValue;
2472
2104
  }
2473
- class SortedSetIterator {
2474
- constructor(iter) {
2475
- this.iter = iter;
2476
- }
2477
- getNext() {
2478
- return this.iter.getNext().key;
2479
- }
2480
- hasNext() {
2481
- return this.iter.hasNext();
2482
- }
2105
+ /**
2106
+ * Returns the local time at which this timestamp was first set.
2107
+ */
2108
+ function getLocalWriteTime(value) {
2109
+ const localWriteTime = normalizeTimestamp(value.mapValue.fields[LOCAL_WRITE_TIME_KEY].timestampValue);
2110
+ return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);
2483
2111
  }
2484
2112
 
2485
2113
  /**
@@ -2498,323 +2126,347 @@ class SortedSetIterator {
2498
2126
  * See the License for the specific language governing permissions and
2499
2127
  * limitations under the License.
2500
2128
  */
2501
- /**
2502
- * Provides a set of fields that can be used to partially patch a document.
2503
- * FieldMask is used in conjunction with ObjectValue.
2504
- * Examples:
2505
- * foo - Overwrites foo entirely with the provided value. If foo is not
2506
- * present in the companion ObjectValue, the field is deleted.
2507
- * foo.bar - Overwrites only the field bar of the object foo.
2508
- * If foo is not an object, foo is replaced with an object
2509
- * containing foo
2510
- */
2511
- class FieldMask {
2512
- constructor(fields) {
2513
- this.fields = fields;
2514
- // TODO(dimond): validation of FieldMask
2515
- // Sort the field mask to support `FieldMask.isEqual()` and assert below.
2516
- fields.sort(FieldPath$1.comparator);
2517
- }
2518
- static empty() {
2519
- return new FieldMask([]);
2520
- }
2521
- /**
2522
- * Returns a new FieldMask object that is the result of adding all the given
2523
- * fields paths to this field mask.
2524
- */
2525
- unionWith(extraFields) {
2526
- let mergedMaskSet = new SortedSet(FieldPath$1.comparator);
2527
- for (const fieldPath of this.fields) {
2528
- mergedMaskSet = mergedMaskSet.add(fieldPath);
2529
- }
2530
- for (const fieldPath of extraFields) {
2531
- mergedMaskSet = mergedMaskSet.add(fieldPath);
2129
+ const MAX_VALUE_TYPE = '__max__';
2130
+ const MAX_VALUE = {
2131
+ mapValue: {
2132
+ fields: {
2133
+ '__type__': { stringValue: MAX_VALUE_TYPE }
2532
2134
  }
2533
- return new FieldMask(mergedMaskSet.toArray());
2534
2135
  }
2535
- /**
2536
- * Verifies that `fieldPath` is included by at least one field in this field
2537
- * mask.
2538
- *
2539
- * This is an O(n) operation, where `n` is the size of the field mask.
2540
- */
2541
- covers(fieldPath) {
2542
- for (const fieldMaskPath of this.fields) {
2543
- if (fieldMaskPath.isPrefixOf(fieldPath)) {
2544
- return true;
2545
- }
2546
- }
2547
- return false;
2136
+ };
2137
+ /** Extracts the backend's type order for the provided value. */
2138
+ function typeOrder(value) {
2139
+ if ('nullValue' in value) {
2140
+ return 0 /* TypeOrder.NullValue */;
2548
2141
  }
2549
- isEqual(other) {
2550
- return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));
2142
+ else if ('booleanValue' in value) {
2143
+ return 1 /* TypeOrder.BooleanValue */;
2551
2144
  }
2552
- }
2553
-
2554
- /**
2555
- * @license
2556
- * Copyright 2020 Google LLC
2557
- *
2558
- * Licensed under the Apache License, Version 2.0 (the "License");
2559
- * you may not use this file except in compliance with the License.
2560
- * You may obtain a copy of the License at
2561
- *
2562
- * http://www.apache.org/licenses/LICENSE-2.0
2563
- *
2564
- * Unless required by applicable law or agreed to in writing, software
2565
- * distributed under the License is distributed on an "AS IS" BASIS,
2566
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2567
- * See the License for the specific language governing permissions and
2568
- * limitations under the License.
2569
- */
2570
- /** Converts a Base64 encoded string to a binary string. */
2571
- function decodeBase64(encoded) {
2572
- // Note: We used to validate the base64 string here via a regular expression.
2573
- // This was removed to improve the performance of indexing.
2574
- return Buffer.from(encoded, 'base64').toString('binary');
2575
- }
2576
- /** Converts a binary string to a Base64 encoded string. */
2577
- function encodeBase64(raw) {
2578
- return Buffer.from(raw, 'binary').toString('base64');
2579
- }
2580
-
2581
- /**
2582
- * @license
2583
- * Copyright 2020 Google LLC
2584
- *
2585
- * Licensed under the Apache License, Version 2.0 (the "License");
2586
- * you may not use this file except in compliance with the License.
2587
- * You may obtain a copy of the License at
2588
- *
2589
- * http://www.apache.org/licenses/LICENSE-2.0
2590
- *
2591
- * Unless required by applicable law or agreed to in writing, software
2592
- * distributed under the License is distributed on an "AS IS" BASIS,
2593
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2594
- * See the License for the specific language governing permissions and
2595
- * limitations under the License.
2596
- */
2597
- /**
2598
- * Immutable class that represents a "proto" byte string.
2599
- *
2600
- * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
2601
- * sent on the wire. This class abstracts away this differentiation by holding
2602
- * the proto byte string in a common class that must be converted into a string
2603
- * before being sent as a proto.
2604
- * @internal
2605
- */
2606
- class ByteString {
2607
- constructor(binaryString) {
2608
- this.binaryString = binaryString;
2145
+ else if ('integerValue' in value || 'doubleValue' in value) {
2146
+ return 2 /* TypeOrder.NumberValue */;
2609
2147
  }
2610
- static fromBase64String(base64) {
2611
- const binaryString = decodeBase64(base64);
2612
- return new ByteString(binaryString);
2148
+ else if ('timestampValue' in value) {
2149
+ return 3 /* TypeOrder.TimestampValue */;
2613
2150
  }
2614
- static fromUint8Array(array) {
2615
- // TODO(indexing); Remove the copy of the byte string here as this method
2616
- // is frequently called during indexing.
2617
- const binaryString = binaryStringFromUint8Array(array);
2618
- return new ByteString(binaryString);
2151
+ else if ('stringValue' in value) {
2152
+ return 5 /* TypeOrder.StringValue */;
2619
2153
  }
2620
- [Symbol.iterator]() {
2621
- let i = 0;
2622
- return {
2623
- next: () => {
2624
- if (i < this.binaryString.length) {
2625
- return { value: this.binaryString.charCodeAt(i++), done: false };
2626
- }
2627
- else {
2628
- return { value: undefined, done: true };
2629
- }
2630
- }
2631
- };
2154
+ else if ('bytesValue' in value) {
2155
+ return 6 /* TypeOrder.BlobValue */;
2632
2156
  }
2633
- toBase64() {
2634
- return encodeBase64(this.binaryString);
2157
+ else if ('referenceValue' in value) {
2158
+ return 7 /* TypeOrder.RefValue */;
2635
2159
  }
2636
- toUint8Array() {
2637
- return uint8ArrayFromBinaryString(this.binaryString);
2160
+ else if ('geoPointValue' in value) {
2161
+ return 8 /* TypeOrder.GeoPointValue */;
2638
2162
  }
2639
- approximateByteSize() {
2640
- return this.binaryString.length * 2;
2163
+ else if ('arrayValue' in value) {
2164
+ return 9 /* TypeOrder.ArrayValue */;
2641
2165
  }
2642
- compareTo(other) {
2643
- return primitiveComparator(this.binaryString, other.binaryString);
2166
+ else if ('mapValue' in value) {
2167
+ if (isServerTimestamp(value)) {
2168
+ return 4 /* TypeOrder.ServerTimestampValue */;
2169
+ }
2170
+ else if (isMaxValue(value)) {
2171
+ return 9007199254740991 /* TypeOrder.MaxValue */;
2172
+ }
2173
+ return 10 /* TypeOrder.ObjectValue */;
2644
2174
  }
2645
- isEqual(other) {
2646
- return this.binaryString === other.binaryString;
2175
+ else {
2176
+ return fail();
2647
2177
  }
2648
2178
  }
2649
- ByteString.EMPTY_BYTE_STRING = new ByteString('');
2650
- /**
2651
- * Helper function to convert an Uint8array to a binary string.
2652
- */
2653
- function binaryStringFromUint8Array(array) {
2654
- let binaryString = '';
2655
- for (let i = 0; i < array.length; ++i) {
2656
- binaryString += String.fromCharCode(array[i]);
2179
+ /** Tests `left` and `right` for equality based on the backend semantics. */
2180
+ function valueEquals(left, right) {
2181
+ if (left === right) {
2182
+ return true;
2183
+ }
2184
+ const leftType = typeOrder(left);
2185
+ const rightType = typeOrder(right);
2186
+ if (leftType !== rightType) {
2187
+ return false;
2188
+ }
2189
+ switch (leftType) {
2190
+ case 0 /* TypeOrder.NullValue */:
2191
+ return true;
2192
+ case 1 /* TypeOrder.BooleanValue */:
2193
+ return left.booleanValue === right.booleanValue;
2194
+ case 4 /* TypeOrder.ServerTimestampValue */:
2195
+ return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));
2196
+ case 3 /* TypeOrder.TimestampValue */:
2197
+ return timestampEquals(left, right);
2198
+ case 5 /* TypeOrder.StringValue */:
2199
+ return left.stringValue === right.stringValue;
2200
+ case 6 /* TypeOrder.BlobValue */:
2201
+ return blobEquals(left, right);
2202
+ case 7 /* TypeOrder.RefValue */:
2203
+ return left.referenceValue === right.referenceValue;
2204
+ case 8 /* TypeOrder.GeoPointValue */:
2205
+ return geoPointEquals(left, right);
2206
+ case 2 /* TypeOrder.NumberValue */:
2207
+ return numberEquals(left, right);
2208
+ case 9 /* TypeOrder.ArrayValue */:
2209
+ return arrayEquals(left.arrayValue.values || [], right.arrayValue.values || [], valueEquals);
2210
+ case 10 /* TypeOrder.ObjectValue */:
2211
+ return objectEquals(left, right);
2212
+ case 9007199254740991 /* TypeOrder.MaxValue */:
2213
+ return true;
2214
+ default:
2215
+ return fail();
2657
2216
  }
2658
- return binaryString;
2659
2217
  }
2660
- /**
2661
- * Helper function to convert a binary string to an Uint8Array.
2662
- */
2663
- function uint8ArrayFromBinaryString(binaryString) {
2664
- const buffer = new Uint8Array(binaryString.length);
2665
- for (let i = 0; i < binaryString.length; i++) {
2666
- buffer[i] = binaryString.charCodeAt(i);
2218
+ function timestampEquals(left, right) {
2219
+ if (typeof left.timestampValue === 'string' &&
2220
+ typeof right.timestampValue === 'string' &&
2221
+ left.timestampValue.length === right.timestampValue.length) {
2222
+ // Use string equality for ISO 8601 timestamps
2223
+ return left.timestampValue === right.timestampValue;
2667
2224
  }
2668
- return buffer;
2669
- }
2670
-
2671
- /**
2672
- * @license
2673
- * Copyright 2020 Google LLC
2674
- *
2675
- * Licensed under the Apache License, Version 2.0 (the "License");
2676
- * you may not use this file except in compliance with the License.
2677
- * You may obtain a copy of the License at
2678
- *
2679
- * http://www.apache.org/licenses/LICENSE-2.0
2680
- *
2681
- * Unless required by applicable law or agreed to in writing, software
2682
- * distributed under the License is distributed on an "AS IS" BASIS,
2683
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2684
- * See the License for the specific language governing permissions and
2685
- * limitations under the License.
2686
- */
2687
- // A RegExp matching ISO 8601 UTC timestamps with optional fraction.
2688
- const ISO_TIMESTAMP_REG_EXP = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
2689
- /**
2690
- * Converts the possible Proto values for a timestamp value into a "seconds and
2691
- * nanos" representation.
2692
- */
2693
- function normalizeTimestamp(date) {
2694
- hardAssert(!!date);
2695
- // The json interface (for the browser) will return an iso timestamp string,
2696
- // while the proto js library (for node) will return a
2697
- // google.protobuf.Timestamp instance.
2698
- if (typeof date === 'string') {
2699
- // The date string can have higher precision (nanos) than the Date class
2700
- // (millis), so we do some custom parsing here.
2701
- // Parse the nanos right out of the string.
2702
- let nanos = 0;
2703
- const fraction = ISO_TIMESTAMP_REG_EXP.exec(date);
2704
- hardAssert(!!fraction);
2705
- if (fraction[1]) {
2706
- // Pad the fraction out to 9 digits (nanos).
2707
- let nanoStr = fraction[1];
2708
- nanoStr = (nanoStr + '000000000').substr(0, 9);
2709
- nanos = Number(nanoStr);
2710
- }
2711
- // Parse the date to get the seconds.
2712
- const parsedDate = new Date(date);
2713
- const seconds = Math.floor(parsedDate.getTime() / 1000);
2714
- return { seconds, nanos };
2225
+ const leftTimestamp = normalizeTimestamp(left.timestampValue);
2226
+ const rightTimestamp = normalizeTimestamp(right.timestampValue);
2227
+ return (leftTimestamp.seconds === rightTimestamp.seconds &&
2228
+ leftTimestamp.nanos === rightTimestamp.nanos);
2229
+ }
2230
+ function geoPointEquals(left, right) {
2231
+ return (normalizeNumber(left.geoPointValue.latitude) ===
2232
+ normalizeNumber(right.geoPointValue.latitude) &&
2233
+ normalizeNumber(left.geoPointValue.longitude) ===
2234
+ normalizeNumber(right.geoPointValue.longitude));
2235
+ }
2236
+ function blobEquals(left, right) {
2237
+ return normalizeByteString(left.bytesValue).isEqual(normalizeByteString(right.bytesValue));
2238
+ }
2239
+ function numberEquals(left, right) {
2240
+ if ('integerValue' in left && 'integerValue' in right) {
2241
+ return (normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue));
2715
2242
  }
2716
- else {
2717
- // TODO(b/37282237): Use strings for Proto3 timestamps
2718
- // assert(!this.options.useProto3Json,
2719
- // 'The timestamp instance format requires Proto JS.');
2720
- const seconds = normalizeNumber(date.seconds);
2721
- const nanos = normalizeNumber(date.nanos);
2722
- return { seconds, nanos };
2243
+ else if ('doubleValue' in left && 'doubleValue' in right) {
2244
+ const n1 = normalizeNumber(left.doubleValue);
2245
+ const n2 = normalizeNumber(right.doubleValue);
2246
+ if (n1 === n2) {
2247
+ return isNegativeZero(n1) === isNegativeZero(n2);
2248
+ }
2249
+ else {
2250
+ return isNaN(n1) && isNaN(n2);
2251
+ }
2723
2252
  }
2253
+ return false;
2724
2254
  }
2725
- /**
2726
- * Converts the possible Proto types for numbers into a JavaScript number.
2727
- * Returns 0 if the value is not numeric.
2728
- */
2729
- function normalizeNumber(value) {
2730
- // TODO(bjornick): Handle int64 greater than 53 bits.
2731
- if (typeof value === 'number') {
2732
- return value;
2255
+ function objectEquals(left, right) {
2256
+ const leftMap = left.mapValue.fields || {};
2257
+ const rightMap = right.mapValue.fields || {};
2258
+ if (objectSize(leftMap) !== objectSize(rightMap)) {
2259
+ return false;
2733
2260
  }
2734
- else if (typeof value === 'string') {
2735
- return Number(value);
2261
+ for (const key in leftMap) {
2262
+ if (leftMap.hasOwnProperty(key)) {
2263
+ if (rightMap[key] === undefined ||
2264
+ !valueEquals(leftMap[key], rightMap[key])) {
2265
+ return false;
2266
+ }
2267
+ }
2736
2268
  }
2737
- else {
2269
+ return true;
2270
+ }
2271
+ /** Returns true if the ArrayValue contains the specified element. */
2272
+ function arrayValueContains(haystack, needle) {
2273
+ return ((haystack.values || []).find(v => valueEquals(v, needle)) !== undefined);
2274
+ }
2275
+ function valueCompare(left, right) {
2276
+ if (left === right) {
2738
2277
  return 0;
2739
2278
  }
2279
+ const leftType = typeOrder(left);
2280
+ const rightType = typeOrder(right);
2281
+ if (leftType !== rightType) {
2282
+ return primitiveComparator(leftType, rightType);
2283
+ }
2284
+ switch (leftType) {
2285
+ case 0 /* TypeOrder.NullValue */:
2286
+ case 9007199254740991 /* TypeOrder.MaxValue */:
2287
+ return 0;
2288
+ case 1 /* TypeOrder.BooleanValue */:
2289
+ return primitiveComparator(left.booleanValue, right.booleanValue);
2290
+ case 2 /* TypeOrder.NumberValue */:
2291
+ return compareNumbers(left, right);
2292
+ case 3 /* TypeOrder.TimestampValue */:
2293
+ return compareTimestamps(left.timestampValue, right.timestampValue);
2294
+ case 4 /* TypeOrder.ServerTimestampValue */:
2295
+ return compareTimestamps(getLocalWriteTime(left), getLocalWriteTime(right));
2296
+ case 5 /* TypeOrder.StringValue */:
2297
+ return primitiveComparator(left.stringValue, right.stringValue);
2298
+ case 6 /* TypeOrder.BlobValue */:
2299
+ return compareBlobs(left.bytesValue, right.bytesValue);
2300
+ case 7 /* TypeOrder.RefValue */:
2301
+ return compareReferences(left.referenceValue, right.referenceValue);
2302
+ case 8 /* TypeOrder.GeoPointValue */:
2303
+ return compareGeoPoints(left.geoPointValue, right.geoPointValue);
2304
+ case 9 /* TypeOrder.ArrayValue */:
2305
+ return compareArrays(left.arrayValue, right.arrayValue);
2306
+ case 10 /* TypeOrder.ObjectValue */:
2307
+ return compareMaps(left.mapValue, right.mapValue);
2308
+ default:
2309
+ throw fail();
2310
+ }
2740
2311
  }
2741
- /** Converts the possible Proto types for Blobs into a ByteString. */
2742
- function normalizeByteString(blob) {
2743
- if (typeof blob === 'string') {
2744
- return ByteString.fromBase64String(blob);
2312
+ function compareNumbers(left, right) {
2313
+ const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);
2314
+ const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);
2315
+ if (leftNumber < rightNumber) {
2316
+ return -1;
2317
+ }
2318
+ else if (leftNumber > rightNumber) {
2319
+ return 1;
2320
+ }
2321
+ else if (leftNumber === rightNumber) {
2322
+ return 0;
2745
2323
  }
2746
2324
  else {
2747
- return ByteString.fromUint8Array(blob);
2325
+ // one or both are NaN.
2326
+ if (isNaN(leftNumber)) {
2327
+ return isNaN(rightNumber) ? 0 : -1;
2328
+ }
2329
+ else {
2330
+ return 1;
2331
+ }
2748
2332
  }
2749
- }
2750
-
2751
- /**
2752
- * @license
2753
- * Copyright 2020 Google LLC
2754
- *
2755
- * Licensed under the Apache License, Version 2.0 (the "License");
2756
- * you may not use this file except in compliance with the License.
2757
- * You may obtain a copy of the License at
2758
- *
2759
- * http://www.apache.org/licenses/LICENSE-2.0
2760
- *
2761
- * Unless required by applicable law or agreed to in writing, software
2762
- * distributed under the License is distributed on an "AS IS" BASIS,
2763
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2764
- * See the License for the specific language governing permissions and
2765
- * limitations under the License.
2766
- */
2767
- /**
2768
- * Represents a locally-applied ServerTimestamp.
2769
- *
2770
- * Server Timestamps are backed by MapValues that contain an internal field
2771
- * `__type__` with a value of `server_timestamp`. The previous value and local
2772
- * write time are stored in its `__previous_value__` and `__local_write_time__`
2773
- * fields respectively.
2774
- *
2775
- * Notes:
2776
- * - ServerTimestampValue instances are created as the result of applying a
2777
- * transform. They can only exist in the local view of a document. Therefore
2778
- * they do not need to be parsed or serialized.
2779
- * - When evaluated locally (e.g. for snapshot.data()), they by default
2780
- * evaluate to `null`. This behavior can be configured by passing custom
2781
- * FieldValueOptions to value().
2782
- * - With respect to other ServerTimestampValues, they sort by their
2783
- * localWriteTime.
2784
- */
2785
- const SERVER_TIMESTAMP_SENTINEL = 'server_timestamp';
2786
- const TYPE_KEY = '__type__';
2787
- const PREVIOUS_VALUE_KEY = '__previous_value__';
2788
- const LOCAL_WRITE_TIME_KEY = '__local_write_time__';
2789
- function isServerTimestamp(value) {
2790
- var _a, _b;
2791
- const type = (_b = (((_a = value === null || value === void 0 ? void 0 : value.mapValue) === null || _a === void 0 ? void 0 : _a.fields) || {})[TYPE_KEY]) === null || _b === void 0 ? void 0 : _b.stringValue;
2792
- return type === SERVER_TIMESTAMP_SENTINEL;
2793
2333
  }
2794
- /**
2795
- * Returns the value of the field before this ServerTimestamp was set.
2796
- *
2797
- * Preserving the previous values allows the user to display the last resoled
2798
- * value until the backend responds with the timestamp.
2799
- */
2800
- function getPreviousValue(value) {
2801
- const previousValue = value.mapValue.fields[PREVIOUS_VALUE_KEY];
2802
- if (isServerTimestamp(previousValue)) {
2803
- return getPreviousValue(previousValue);
2334
+ function compareTimestamps(left, right) {
2335
+ if (typeof left === 'string' &&
2336
+ typeof right === 'string' &&
2337
+ left.length === right.length) {
2338
+ return primitiveComparator(left, right);
2804
2339
  }
2805
- return previousValue;
2340
+ const leftTimestamp = normalizeTimestamp(left);
2341
+ const rightTimestamp = normalizeTimestamp(right);
2342
+ const comparison = primitiveComparator(leftTimestamp.seconds, rightTimestamp.seconds);
2343
+ if (comparison !== 0) {
2344
+ return comparison;
2345
+ }
2346
+ return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);
2806
2347
  }
2807
- /**
2808
- * Returns the local time at which this timestamp was first set.
2809
- */
2810
- function getLocalWriteTime(value) {
2811
- const localWriteTime = normalizeTimestamp(value.mapValue.fields[LOCAL_WRITE_TIME_KEY].timestampValue);
2812
- return new Timestamp(localWriteTime.seconds, localWriteTime.nanos);
2348
+ function compareReferences(leftPath, rightPath) {
2349
+ const leftSegments = leftPath.split('/');
2350
+ const rightSegments = rightPath.split('/');
2351
+ for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {
2352
+ const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);
2353
+ if (comparison !== 0) {
2354
+ return comparison;
2355
+ }
2356
+ }
2357
+ return primitiveComparator(leftSegments.length, rightSegments.length);
2358
+ }
2359
+ function compareGeoPoints(left, right) {
2360
+ const comparison = primitiveComparator(normalizeNumber(left.latitude), normalizeNumber(right.latitude));
2361
+ if (comparison !== 0) {
2362
+ return comparison;
2363
+ }
2364
+ return primitiveComparator(normalizeNumber(left.longitude), normalizeNumber(right.longitude));
2365
+ }
2366
+ function compareBlobs(left, right) {
2367
+ const leftBytes = normalizeByteString(left);
2368
+ const rightBytes = normalizeByteString(right);
2369
+ return leftBytes.compareTo(rightBytes);
2370
+ }
2371
+ function compareArrays(left, right) {
2372
+ const leftArray = left.values || [];
2373
+ const rightArray = right.values || [];
2374
+ for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {
2375
+ const compare = valueCompare(leftArray[i], rightArray[i]);
2376
+ if (compare) {
2377
+ return compare;
2378
+ }
2379
+ }
2380
+ return primitiveComparator(leftArray.length, rightArray.length);
2381
+ }
2382
+ function compareMaps(left, right) {
2383
+ if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {
2384
+ return 0;
2385
+ }
2386
+ else if (left === MAX_VALUE.mapValue) {
2387
+ return 1;
2388
+ }
2389
+ else if (right === MAX_VALUE.mapValue) {
2390
+ return -1;
2391
+ }
2392
+ const leftMap = left.fields || {};
2393
+ const leftKeys = Object.keys(leftMap);
2394
+ const rightMap = right.fields || {};
2395
+ const rightKeys = Object.keys(rightMap);
2396
+ // Even though MapValues are likely sorted correctly based on their insertion
2397
+ // order (e.g. when received from the backend), local modifications can bring
2398
+ // elements out of order. We need to re-sort the elements to ensure that
2399
+ // canonical IDs are independent of insertion order.
2400
+ leftKeys.sort();
2401
+ rightKeys.sort();
2402
+ for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {
2403
+ const keyCompare = primitiveComparator(leftKeys[i], rightKeys[i]);
2404
+ if (keyCompare !== 0) {
2405
+ return keyCompare;
2406
+ }
2407
+ const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);
2408
+ if (compare !== 0) {
2409
+ return compare;
2410
+ }
2411
+ }
2412
+ return primitiveComparator(leftKeys.length, rightKeys.length);
2413
+ }
2414
+ /** Returns a reference value for the provided database and key. */
2415
+ function refValue(databaseId, key) {
2416
+ return {
2417
+ referenceValue: `projects/${databaseId.projectId}/databases/${databaseId.database}/documents/${key.path.canonicalString()}`
2418
+ };
2419
+ }
2420
+ /** Returns true if `value` is an ArrayValue. */
2421
+ function isArray(value) {
2422
+ return !!value && 'arrayValue' in value;
2423
+ }
2424
+ /** Returns true if `value` is a NullValue. */
2425
+ function isNullValue(value) {
2426
+ return !!value && 'nullValue' in value;
2427
+ }
2428
+ /** Returns true if `value` is NaN. */
2429
+ function isNanValue(value) {
2430
+ return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));
2431
+ }
2432
+ /** Returns true if `value` is a MapValue. */
2433
+ function isMapValue(value) {
2434
+ return !!value && 'mapValue' in value;
2435
+ }
2436
+ /** Creates a deep copy of `source`. */
2437
+ function deepClone(source) {
2438
+ if (source.geoPointValue) {
2439
+ return { geoPointValue: Object.assign({}, source.geoPointValue) };
2440
+ }
2441
+ else if (source.timestampValue &&
2442
+ typeof source.timestampValue === 'object') {
2443
+ return { timestampValue: Object.assign({}, source.timestampValue) };
2444
+ }
2445
+ else if (source.mapValue) {
2446
+ const target = { mapValue: { fields: {} } };
2447
+ forEach(source.mapValue.fields, (key, val) => (target.mapValue.fields[key] = deepClone(val)));
2448
+ return target;
2449
+ }
2450
+ else if (source.arrayValue) {
2451
+ const target = { arrayValue: { values: [] } };
2452
+ for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {
2453
+ target.arrayValue.values[i] = deepClone(source.arrayValue.values[i]);
2454
+ }
2455
+ return target;
2456
+ }
2457
+ else {
2458
+ return Object.assign({}, source);
2459
+ }
2460
+ }
2461
+ /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */
2462
+ function isMaxValue(value) {
2463
+ return ((((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===
2464
+ MAX_VALUE_TYPE);
2813
2465
  }
2814
2466
 
2815
2467
  /**
2816
2468
  * @license
2817
- * Copyright 2017 Google LLC
2469
+ * Copyright 2022 Google LLC
2818
2470
  *
2819
2471
  * Licensed under the Apache License, Version 2.0 (the "License");
2820
2472
  * you may not use this file except in compliance with the License.
@@ -2829,32 +2481,49 @@ function getLocalWriteTime(value) {
2829
2481
  * limitations under the License.
2830
2482
  */
2831
2483
  /**
2832
- * Returns whether a variable is either undefined or null.
2484
+ * Represents a bound of a query.
2485
+ *
2486
+ * The bound is specified with the given components representing a position and
2487
+ * whether it's just before or just after the position (relative to whatever the
2488
+ * query order is).
2489
+ *
2490
+ * The position represents a logical index position for a query. It's a prefix
2491
+ * of values for the (potentially implicit) order by clauses of a query.
2492
+ *
2493
+ * Bound provides a function to determine whether a document comes before or
2494
+ * after a bound. This is influenced by whether the position is just before or
2495
+ * just after the provided values.
2833
2496
  */
2834
- function isNullOrUndefined(value) {
2835
- return value === null || value === undefined;
2836
- }
2837
- /** Returns whether the value represents -0. */
2838
- function isNegativeZero(value) {
2839
- // Detect if the value is -0.0. Based on polyfill from
2840
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
2841
- return value === 0 && 1 / value === 1 / -0;
2497
+ class Bound {
2498
+ constructor(position, inclusive) {
2499
+ this.position = position;
2500
+ this.inclusive = inclusive;
2501
+ }
2842
2502
  }
2843
- /**
2844
- * Returns whether a value is an integer and in the safe integer range
2845
- * @param value - The value to test for being an integer and in the safe range
2846
- */
2847
- function isSafeInteger(value) {
2848
- return (typeof value === 'number' &&
2849
- Number.isInteger(value) &&
2850
- !isNegativeZero(value) &&
2851
- value <= Number.MAX_SAFE_INTEGER &&
2852
- value >= Number.MIN_SAFE_INTEGER);
2503
+ function boundEquals(left, right) {
2504
+ if (left === null) {
2505
+ return right === null;
2506
+ }
2507
+ else if (right === null) {
2508
+ return false;
2509
+ }
2510
+ if (left.inclusive !== right.inclusive ||
2511
+ left.position.length !== right.position.length) {
2512
+ return false;
2513
+ }
2514
+ for (let i = 0; i < left.position.length; i++) {
2515
+ const leftPosition = left.position[i];
2516
+ const rightPosition = right.position[i];
2517
+ if (!valueEquals(leftPosition, rightPosition)) {
2518
+ return false;
2519
+ }
2520
+ }
2521
+ return true;
2853
2522
  }
2854
2523
 
2855
2524
  /**
2856
2525
  * @license
2857
- * Copyright 2020 Google LLC
2526
+ * Copyright 2022 Google LLC
2858
2527
  *
2859
2528
  * Licensed under the Apache License, Version 2.0 (the "License");
2860
2529
  * you may not use this file except in compliance with the License.
@@ -2868,342 +2537,1038 @@ function isSafeInteger(value) {
2868
2537
  * See the License for the specific language governing permissions and
2869
2538
  * limitations under the License.
2870
2539
  */
2871
- const MAX_VALUE_TYPE = '__max__';
2872
- const MAX_VALUE = {
2873
- mapValue: {
2874
- fields: {
2875
- '__type__': { stringValue: MAX_VALUE_TYPE }
2540
+ class Filter {
2541
+ }
2542
+ class FieldFilter extends Filter {
2543
+ constructor(field, op, value) {
2544
+ super();
2545
+ this.field = field;
2546
+ this.op = op;
2547
+ this.value = value;
2548
+ }
2549
+ /**
2550
+ * Creates a filter based on the provided arguments.
2551
+ */
2552
+ static create(field, op, value) {
2553
+ if (field.isKeyField()) {
2554
+ if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) {
2555
+ return this.createKeyFieldInFilter(field, op, value);
2556
+ }
2557
+ else {
2558
+ return new KeyFieldFilter(field, op, value);
2559
+ }
2560
+ }
2561
+ else if (op === "array-contains" /* Operator.ARRAY_CONTAINS */) {
2562
+ return new ArrayContainsFilter(field, value);
2563
+ }
2564
+ else if (op === "in" /* Operator.IN */) {
2565
+ return new InFilter(field, value);
2566
+ }
2567
+ else if (op === "not-in" /* Operator.NOT_IN */) {
2568
+ return new NotInFilter(field, value);
2569
+ }
2570
+ else if (op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) {
2571
+ return new ArrayContainsAnyFilter(field, value);
2572
+ }
2573
+ else {
2574
+ return new FieldFilter(field, op, value);
2575
+ }
2576
+ }
2577
+ static createKeyFieldInFilter(field, op, value) {
2578
+ return op === "in" /* Operator.IN */
2579
+ ? new KeyFieldInFilter(field, value)
2580
+ : new KeyFieldNotInFilter(field, value);
2581
+ }
2582
+ matches(doc) {
2583
+ const other = doc.data.field(this.field);
2584
+ // Types do not have to match in NOT_EQUAL filters.
2585
+ if (this.op === "!=" /* Operator.NOT_EQUAL */) {
2586
+ return (other !== null &&
2587
+ this.matchesComparison(valueCompare(other, this.value)));
2588
+ }
2589
+ // Only compare types with matching backend order (such as double and int).
2590
+ return (other !== null &&
2591
+ typeOrder(this.value) === typeOrder(other) &&
2592
+ this.matchesComparison(valueCompare(other, this.value)));
2593
+ }
2594
+ matchesComparison(comparison) {
2595
+ switch (this.op) {
2596
+ case "<" /* Operator.LESS_THAN */:
2597
+ return comparison < 0;
2598
+ case "<=" /* Operator.LESS_THAN_OR_EQUAL */:
2599
+ return comparison <= 0;
2600
+ case "==" /* Operator.EQUAL */:
2601
+ return comparison === 0;
2602
+ case "!=" /* Operator.NOT_EQUAL */:
2603
+ return comparison !== 0;
2604
+ case ">" /* Operator.GREATER_THAN */:
2605
+ return comparison > 0;
2606
+ case ">=" /* Operator.GREATER_THAN_OR_EQUAL */:
2607
+ return comparison >= 0;
2608
+ default:
2609
+ return fail();
2610
+ }
2611
+ }
2612
+ isInequality() {
2613
+ return ([
2614
+ "<" /* Operator.LESS_THAN */,
2615
+ "<=" /* Operator.LESS_THAN_OR_EQUAL */,
2616
+ ">" /* Operator.GREATER_THAN */,
2617
+ ">=" /* Operator.GREATER_THAN_OR_EQUAL */,
2618
+ "!=" /* Operator.NOT_EQUAL */,
2619
+ "not-in" /* Operator.NOT_IN */
2620
+ ].indexOf(this.op) >= 0);
2621
+ }
2622
+ getFlattenedFilters() {
2623
+ return [this];
2624
+ }
2625
+ getFilters() {
2626
+ return [this];
2627
+ }
2628
+ getFirstInequalityField() {
2629
+ if (this.isInequality()) {
2630
+ return this.field;
2631
+ }
2632
+ return null;
2633
+ }
2634
+ }
2635
+ class CompositeFilter extends Filter {
2636
+ constructor(filters, op) {
2637
+ super();
2638
+ this.filters = filters;
2639
+ this.op = op;
2640
+ this.memoizedFlattenedFilters = null;
2641
+ }
2642
+ /**
2643
+ * Creates a filter based on the provided arguments.
2644
+ */
2645
+ static create(filters, op) {
2646
+ return new CompositeFilter(filters, op);
2647
+ }
2648
+ matches(doc) {
2649
+ if (compositeFilterIsConjunction(this)) {
2650
+ // For conjunctions, all filters must match, so return false if any filter doesn't match.
2651
+ return this.filters.find(filter => !filter.matches(doc)) === undefined;
2652
+ }
2653
+ else {
2654
+ // For disjunctions, at least one filter should match.
2655
+ return this.filters.find(filter => filter.matches(doc)) !== undefined;
2656
+ }
2657
+ }
2658
+ getFlattenedFilters() {
2659
+ if (this.memoizedFlattenedFilters !== null) {
2660
+ return this.memoizedFlattenedFilters;
2661
+ }
2662
+ this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {
2663
+ return result.concat(subfilter.getFlattenedFilters());
2664
+ }, []);
2665
+ return this.memoizedFlattenedFilters;
2666
+ }
2667
+ // Returns a mutable copy of `this.filters`
2668
+ getFilters() {
2669
+ return Object.assign([], this.filters);
2670
+ }
2671
+ getFirstInequalityField() {
2672
+ const found = this.findFirstMatchingFilter(filter => filter.isInequality());
2673
+ if (found !== null) {
2674
+ return found.field;
2675
+ }
2676
+ return null;
2677
+ }
2678
+ // Performs a depth-first search to find and return the first FieldFilter in the composite filter
2679
+ // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the
2680
+ // predicate.
2681
+ findFirstMatchingFilter(predicate) {
2682
+ for (const fieldFilter of this.getFlattenedFilters()) {
2683
+ if (predicate(fieldFilter)) {
2684
+ return fieldFilter;
2685
+ }
2686
+ }
2687
+ return null;
2688
+ }
2689
+ }
2690
+ function compositeFilterIsConjunction(compositeFilter) {
2691
+ return compositeFilter.op === "and" /* CompositeOperator.AND */;
2692
+ }
2693
+ function filterEquals(f1, f2) {
2694
+ if (f1 instanceof FieldFilter) {
2695
+ return fieldFilterEquals(f1, f2);
2696
+ }
2697
+ else if (f1 instanceof CompositeFilter) {
2698
+ return compositeFilterEquals(f1, f2);
2699
+ }
2700
+ else {
2701
+ fail();
2702
+ }
2703
+ }
2704
+ function fieldFilterEquals(f1, f2) {
2705
+ return (f2 instanceof FieldFilter &&
2706
+ f1.op === f2.op &&
2707
+ f1.field.isEqual(f2.field) &&
2708
+ valueEquals(f1.value, f2.value));
2709
+ }
2710
+ function compositeFilterEquals(f1, f2) {
2711
+ if (f2 instanceof CompositeFilter &&
2712
+ f1.op === f2.op &&
2713
+ f1.filters.length === f2.filters.length) {
2714
+ const subFiltersMatch = f1.filters.reduce((result, f1Filter, index) => result && filterEquals(f1Filter, f2.filters[index]), true);
2715
+ return subFiltersMatch;
2716
+ }
2717
+ return false;
2718
+ }
2719
+ /** Filter that matches on key fields (i.e. '__name__'). */
2720
+ class KeyFieldFilter extends FieldFilter {
2721
+ constructor(field, op, value) {
2722
+ super(field, op, value);
2723
+ this.key = DocumentKey.fromName(value.referenceValue);
2724
+ }
2725
+ matches(doc) {
2726
+ const comparison = DocumentKey.comparator(doc.key, this.key);
2727
+ return this.matchesComparison(comparison);
2728
+ }
2729
+ }
2730
+ /** Filter that matches on key fields within an array. */
2731
+ class KeyFieldInFilter extends FieldFilter {
2732
+ constructor(field, value) {
2733
+ super(field, "in" /* Operator.IN */, value);
2734
+ this.keys = extractDocumentKeysFromArrayValue("in" /* Operator.IN */, value);
2735
+ }
2736
+ matches(doc) {
2737
+ return this.keys.some(key => key.isEqual(doc.key));
2738
+ }
2739
+ }
2740
+ /** Filter that matches on key fields not present within an array. */
2741
+ class KeyFieldNotInFilter extends FieldFilter {
2742
+ constructor(field, value) {
2743
+ super(field, "not-in" /* Operator.NOT_IN */, value);
2744
+ this.keys = extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */, value);
2745
+ }
2746
+ matches(doc) {
2747
+ return !this.keys.some(key => key.isEqual(doc.key));
2748
+ }
2749
+ }
2750
+ function extractDocumentKeysFromArrayValue(op, value) {
2751
+ var _a;
2752
+ return (((_a = value.arrayValue) === null || _a === void 0 ? void 0 : _a.values) || []).map(v => {
2753
+ return DocumentKey.fromName(v.referenceValue);
2754
+ });
2755
+ }
2756
+ /** A Filter that implements the array-contains operator. */
2757
+ class ArrayContainsFilter extends FieldFilter {
2758
+ constructor(field, value) {
2759
+ super(field, "array-contains" /* Operator.ARRAY_CONTAINS */, value);
2760
+ }
2761
+ matches(doc) {
2762
+ const other = doc.data.field(this.field);
2763
+ return isArray(other) && arrayValueContains(other.arrayValue, this.value);
2764
+ }
2765
+ }
2766
+ /** A Filter that implements the IN operator. */
2767
+ class InFilter extends FieldFilter {
2768
+ constructor(field, value) {
2769
+ super(field, "in" /* Operator.IN */, value);
2770
+ }
2771
+ matches(doc) {
2772
+ const other = doc.data.field(this.field);
2773
+ return other !== null && arrayValueContains(this.value.arrayValue, other);
2774
+ }
2775
+ }
2776
+ /** A Filter that implements the not-in operator. */
2777
+ class NotInFilter extends FieldFilter {
2778
+ constructor(field, value) {
2779
+ super(field, "not-in" /* Operator.NOT_IN */, value);
2780
+ }
2781
+ matches(doc) {
2782
+ if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) {
2783
+ return false;
2784
+ }
2785
+ const other = doc.data.field(this.field);
2786
+ return other !== null && !arrayValueContains(this.value.arrayValue, other);
2787
+ }
2788
+ }
2789
+ /** A Filter that implements the array-contains-any operator. */
2790
+ class ArrayContainsAnyFilter extends FieldFilter {
2791
+ constructor(field, value) {
2792
+ super(field, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, value);
2793
+ }
2794
+ matches(doc) {
2795
+ const other = doc.data.field(this.field);
2796
+ if (!isArray(other) || !other.arrayValue.values) {
2797
+ return false;
2798
+ }
2799
+ return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val));
2800
+ }
2801
+ }
2802
+
2803
+ /**
2804
+ * @license
2805
+ * Copyright 2022 Google LLC
2806
+ *
2807
+ * Licensed under the Apache License, Version 2.0 (the "License");
2808
+ * you may not use this file except in compliance with the License.
2809
+ * You may obtain a copy of the License at
2810
+ *
2811
+ * http://www.apache.org/licenses/LICENSE-2.0
2812
+ *
2813
+ * Unless required by applicable law or agreed to in writing, software
2814
+ * distributed under the License is distributed on an "AS IS" BASIS,
2815
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2816
+ * See the License for the specific language governing permissions and
2817
+ * limitations under the License.
2818
+ */
2819
+ /**
2820
+ * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
2821
+ */
2822
+ class OrderBy {
2823
+ constructor(field, dir = "asc" /* Direction.ASCENDING */) {
2824
+ this.field = field;
2825
+ this.dir = dir;
2826
+ }
2827
+ }
2828
+ function orderByEquals(left, right) {
2829
+ return left.dir === right.dir && left.field.isEqual(right.field);
2830
+ }
2831
+
2832
+ /**
2833
+ * @license
2834
+ * Copyright 2017 Google LLC
2835
+ *
2836
+ * Licensed under the Apache License, Version 2.0 (the "License");
2837
+ * you may not use this file except in compliance with the License.
2838
+ * You may obtain a copy of the License at
2839
+ *
2840
+ * http://www.apache.org/licenses/LICENSE-2.0
2841
+ *
2842
+ * Unless required by applicable law or agreed to in writing, software
2843
+ * distributed under the License is distributed on an "AS IS" BASIS,
2844
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2845
+ * See the License for the specific language governing permissions and
2846
+ * limitations under the License.
2847
+ */
2848
+ /**
2849
+ * A version of a document in Firestore. This corresponds to the version
2850
+ * timestamp, such as update_time or read_time.
2851
+ */
2852
+ class SnapshotVersion {
2853
+ constructor(timestamp) {
2854
+ this.timestamp = timestamp;
2855
+ }
2856
+ static fromTimestamp(value) {
2857
+ return new SnapshotVersion(value);
2858
+ }
2859
+ static min() {
2860
+ return new SnapshotVersion(new Timestamp(0, 0));
2861
+ }
2862
+ static max() {
2863
+ return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1));
2864
+ }
2865
+ compareTo(other) {
2866
+ return this.timestamp._compareTo(other.timestamp);
2867
+ }
2868
+ isEqual(other) {
2869
+ return this.timestamp.isEqual(other.timestamp);
2870
+ }
2871
+ /** Returns a number representation of the version for use in spec tests. */
2872
+ toMicroseconds() {
2873
+ // Convert to microseconds.
2874
+ return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;
2875
+ }
2876
+ toString() {
2877
+ return 'SnapshotVersion(' + this.timestamp.toString() + ')';
2878
+ }
2879
+ toTimestamp() {
2880
+ return this.timestamp;
2881
+ }
2882
+ }
2883
+
2884
+ /**
2885
+ * @license
2886
+ * Copyright 2017 Google LLC
2887
+ *
2888
+ * Licensed under the Apache License, Version 2.0 (the "License");
2889
+ * you may not use this file except in compliance with the License.
2890
+ * You may obtain a copy of the License at
2891
+ *
2892
+ * http://www.apache.org/licenses/LICENSE-2.0
2893
+ *
2894
+ * Unless required by applicable law or agreed to in writing, software
2895
+ * distributed under the License is distributed on an "AS IS" BASIS,
2896
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2897
+ * See the License for the specific language governing permissions and
2898
+ * limitations under the License.
2899
+ */
2900
+ // An immutable sorted map implementation, based on a Left-leaning Red-Black
2901
+ // tree.
2902
+ class SortedMap {
2903
+ constructor(comparator, root) {
2904
+ this.comparator = comparator;
2905
+ this.root = root ? root : LLRBNode.EMPTY;
2906
+ }
2907
+ // Returns a copy of the map, with the specified key/value added or replaced.
2908
+ insert(key, value) {
2909
+ return new SortedMap(this.comparator, this.root
2910
+ .insert(key, value, this.comparator)
2911
+ .copy(null, null, LLRBNode.BLACK, null, null));
2912
+ }
2913
+ // Returns a copy of the map, with the specified key removed.
2914
+ remove(key) {
2915
+ return new SortedMap(this.comparator, this.root
2916
+ .remove(key, this.comparator)
2917
+ .copy(null, null, LLRBNode.BLACK, null, null));
2918
+ }
2919
+ // Returns the value of the node with the given key, or null.
2920
+ get(key) {
2921
+ let node = this.root;
2922
+ while (!node.isEmpty()) {
2923
+ const cmp = this.comparator(key, node.key);
2924
+ if (cmp === 0) {
2925
+ return node.value;
2926
+ }
2927
+ else if (cmp < 0) {
2928
+ node = node.left;
2929
+ }
2930
+ else if (cmp > 0) {
2931
+ node = node.right;
2932
+ }
2933
+ }
2934
+ return null;
2935
+ }
2936
+ // Returns the index of the element in this sorted map, or -1 if it doesn't
2937
+ // exist.
2938
+ indexOf(key) {
2939
+ // Number of nodes that were pruned when descending right
2940
+ let prunedNodes = 0;
2941
+ let node = this.root;
2942
+ while (!node.isEmpty()) {
2943
+ const cmp = this.comparator(key, node.key);
2944
+ if (cmp === 0) {
2945
+ return prunedNodes + node.left.size;
2946
+ }
2947
+ else if (cmp < 0) {
2948
+ node = node.left;
2949
+ }
2950
+ else {
2951
+ // Count all nodes left of the node plus the node itself
2952
+ prunedNodes += node.left.size + 1;
2953
+ node = node.right;
2954
+ }
2955
+ }
2956
+ // Node not found
2957
+ return -1;
2958
+ }
2959
+ isEmpty() {
2960
+ return this.root.isEmpty();
2961
+ }
2962
+ // Returns the total number of nodes in the map.
2963
+ get size() {
2964
+ return this.root.size;
2965
+ }
2966
+ // Returns the minimum key in the map.
2967
+ minKey() {
2968
+ return this.root.minKey();
2969
+ }
2970
+ // Returns the maximum key in the map.
2971
+ maxKey() {
2972
+ return this.root.maxKey();
2973
+ }
2974
+ // Traverses the map in key order and calls the specified action function
2975
+ // for each key/value pair. If action returns true, traversal is aborted.
2976
+ // Returns the first truthy value returned by action, or the last falsey
2977
+ // value returned by action.
2978
+ inorderTraversal(action) {
2979
+ return this.root.inorderTraversal(action);
2980
+ }
2981
+ forEach(fn) {
2982
+ this.inorderTraversal((k, v) => {
2983
+ fn(k, v);
2984
+ return false;
2985
+ });
2986
+ }
2987
+ toString() {
2988
+ const descriptions = [];
2989
+ this.inorderTraversal((k, v) => {
2990
+ descriptions.push(`${k}:${v}`);
2991
+ return false;
2992
+ });
2993
+ return `{${descriptions.join(', ')}}`;
2994
+ }
2995
+ // Traverses the map in reverse key order and calls the specified action
2996
+ // function for each key/value pair. If action returns true, traversal is
2997
+ // aborted.
2998
+ // Returns the first truthy value returned by action, or the last falsey
2999
+ // value returned by action.
3000
+ reverseTraversal(action) {
3001
+ return this.root.reverseTraversal(action);
3002
+ }
3003
+ // Returns an iterator over the SortedMap.
3004
+ getIterator() {
3005
+ return new SortedMapIterator(this.root, null, this.comparator, false);
3006
+ }
3007
+ getIteratorFrom(key) {
3008
+ return new SortedMapIterator(this.root, key, this.comparator, false);
3009
+ }
3010
+ getReverseIterator() {
3011
+ return new SortedMapIterator(this.root, null, this.comparator, true);
3012
+ }
3013
+ getReverseIteratorFrom(key) {
3014
+ return new SortedMapIterator(this.root, key, this.comparator, true);
3015
+ }
3016
+ } // end SortedMap
3017
+ // An iterator over an LLRBNode.
3018
+ class SortedMapIterator {
3019
+ constructor(node, startKey, comparator, isReverse) {
3020
+ this.isReverse = isReverse;
3021
+ this.nodeStack = [];
3022
+ let cmp = 1;
3023
+ while (!node.isEmpty()) {
3024
+ cmp = startKey ? comparator(node.key, startKey) : 1;
3025
+ // flip the comparison if we're going in reverse
3026
+ if (startKey && isReverse) {
3027
+ cmp *= -1;
3028
+ }
3029
+ if (cmp < 0) {
3030
+ // This node is less than our start key. ignore it
3031
+ if (this.isReverse) {
3032
+ node = node.left;
3033
+ }
3034
+ else {
3035
+ node = node.right;
3036
+ }
3037
+ }
3038
+ else if (cmp === 0) {
3039
+ // This node is exactly equal to our start key. Push it on the stack,
3040
+ // but stop iterating;
3041
+ this.nodeStack.push(node);
3042
+ break;
3043
+ }
3044
+ else {
3045
+ // This node is greater than our start key, add it to the stack and move
3046
+ // to the next one
3047
+ this.nodeStack.push(node);
3048
+ if (this.isReverse) {
3049
+ node = node.right;
3050
+ }
3051
+ else {
3052
+ node = node.left;
3053
+ }
3054
+ }
3055
+ }
3056
+ }
3057
+ getNext() {
3058
+ let node = this.nodeStack.pop();
3059
+ const result = { key: node.key, value: node.value };
3060
+ if (this.isReverse) {
3061
+ node = node.left;
3062
+ while (!node.isEmpty()) {
3063
+ this.nodeStack.push(node);
3064
+ node = node.right;
3065
+ }
3066
+ }
3067
+ else {
3068
+ node = node.right;
3069
+ while (!node.isEmpty()) {
3070
+ this.nodeStack.push(node);
3071
+ node = node.left;
3072
+ }
3073
+ }
3074
+ return result;
3075
+ }
3076
+ hasNext() {
3077
+ return this.nodeStack.length > 0;
3078
+ }
3079
+ peek() {
3080
+ if (this.nodeStack.length === 0) {
3081
+ return null;
3082
+ }
3083
+ const node = this.nodeStack[this.nodeStack.length - 1];
3084
+ return { key: node.key, value: node.value };
3085
+ }
3086
+ } // end SortedMapIterator
3087
+ // Represents a node in a Left-leaning Red-Black tree.
3088
+ class LLRBNode {
3089
+ constructor(key, value, color, left, right) {
3090
+ this.key = key;
3091
+ this.value = value;
3092
+ this.color = color != null ? color : LLRBNode.RED;
3093
+ this.left = left != null ? left : LLRBNode.EMPTY;
3094
+ this.right = right != null ? right : LLRBNode.EMPTY;
3095
+ this.size = this.left.size + 1 + this.right.size;
3096
+ }
3097
+ // Returns a copy of the current node, optionally replacing pieces of it.
3098
+ copy(key, value, color, left, right) {
3099
+ return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
3100
+ }
3101
+ isEmpty() {
3102
+ return false;
3103
+ }
3104
+ // Traverses the tree in key order and calls the specified action function
3105
+ // for each node. If action returns true, traversal is aborted.
3106
+ // Returns the first truthy value returned by action, or the last falsey
3107
+ // value returned by action.
3108
+ inorderTraversal(action) {
3109
+ return (this.left.inorderTraversal(action) ||
3110
+ action(this.key, this.value) ||
3111
+ this.right.inorderTraversal(action));
3112
+ }
3113
+ // Traverses the tree in reverse key order and calls the specified action
3114
+ // function for each node. If action returns true, traversal is aborted.
3115
+ // Returns the first truthy value returned by action, or the last falsey
3116
+ // value returned by action.
3117
+ reverseTraversal(action) {
3118
+ return (this.right.reverseTraversal(action) ||
3119
+ action(this.key, this.value) ||
3120
+ this.left.reverseTraversal(action));
3121
+ }
3122
+ // Returns the minimum node in the tree.
3123
+ min() {
3124
+ if (this.left.isEmpty()) {
3125
+ return this;
3126
+ }
3127
+ else {
3128
+ return this.left.min();
3129
+ }
3130
+ }
3131
+ // Returns the maximum key in the tree.
3132
+ minKey() {
3133
+ return this.min().key;
3134
+ }
3135
+ // Returns the maximum key in the tree.
3136
+ maxKey() {
3137
+ if (this.right.isEmpty()) {
3138
+ return this.key;
3139
+ }
3140
+ else {
3141
+ return this.right.maxKey();
3142
+ }
3143
+ }
3144
+ // Returns new tree, with the key/value added.
3145
+ insert(key, value, comparator) {
3146
+ let n = this;
3147
+ const cmp = comparator(key, n.key);
3148
+ if (cmp < 0) {
3149
+ n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
3150
+ }
3151
+ else if (cmp === 0) {
3152
+ n = n.copy(null, value, null, null, null);
3153
+ }
3154
+ else {
3155
+ n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
3156
+ }
3157
+ return n.fixUp();
3158
+ }
3159
+ removeMin() {
3160
+ if (this.left.isEmpty()) {
3161
+ return LLRBNode.EMPTY;
3162
+ }
3163
+ let n = this;
3164
+ if (!n.left.isRed() && !n.left.left.isRed()) {
3165
+ n = n.moveRedLeft();
3166
+ }
3167
+ n = n.copy(null, null, null, n.left.removeMin(), null);
3168
+ return n.fixUp();
3169
+ }
3170
+ // Returns new tree, with the specified item removed.
3171
+ remove(key, comparator) {
3172
+ let smallest;
3173
+ let n = this;
3174
+ if (comparator(key, n.key) < 0) {
3175
+ if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {
3176
+ n = n.moveRedLeft();
3177
+ }
3178
+ n = n.copy(null, null, null, n.left.remove(key, comparator), null);
3179
+ }
3180
+ else {
3181
+ if (n.left.isRed()) {
3182
+ n = n.rotateRight();
3183
+ }
3184
+ if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {
3185
+ n = n.moveRedRight();
3186
+ }
3187
+ if (comparator(key, n.key) === 0) {
3188
+ if (n.right.isEmpty()) {
3189
+ return LLRBNode.EMPTY;
3190
+ }
3191
+ else {
3192
+ smallest = n.right.min();
3193
+ n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());
3194
+ }
3195
+ }
3196
+ n = n.copy(null, null, null, null, n.right.remove(key, comparator));
3197
+ }
3198
+ return n.fixUp();
3199
+ }
3200
+ isRed() {
3201
+ return this.color;
3202
+ }
3203
+ // Returns new tree after performing any needed rotations.
3204
+ fixUp() {
3205
+ let n = this;
3206
+ if (n.right.isRed() && !n.left.isRed()) {
3207
+ n = n.rotateLeft();
3208
+ }
3209
+ if (n.left.isRed() && n.left.left.isRed()) {
3210
+ n = n.rotateRight();
3211
+ }
3212
+ if (n.left.isRed() && n.right.isRed()) {
3213
+ n = n.colorFlip();
3214
+ }
3215
+ return n;
3216
+ }
3217
+ moveRedLeft() {
3218
+ let n = this.colorFlip();
3219
+ if (n.right.left.isRed()) {
3220
+ n = n.copy(null, null, null, null, n.right.rotateRight());
3221
+ n = n.rotateLeft();
3222
+ n = n.colorFlip();
3223
+ }
3224
+ return n;
3225
+ }
3226
+ moveRedRight() {
3227
+ let n = this.colorFlip();
3228
+ if (n.left.left.isRed()) {
3229
+ n = n.rotateRight();
3230
+ n = n.colorFlip();
3231
+ }
3232
+ return n;
3233
+ }
3234
+ rotateLeft() {
3235
+ const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
3236
+ return this.right.copy(null, null, this.color, nl, null);
3237
+ }
3238
+ rotateRight() {
3239
+ const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
3240
+ return this.left.copy(null, null, this.color, null, nr);
3241
+ }
3242
+ colorFlip() {
3243
+ const left = this.left.copy(null, null, !this.left.color, null, null);
3244
+ const right = this.right.copy(null, null, !this.right.color, null, null);
3245
+ return this.copy(null, null, !this.color, left, right);
3246
+ }
3247
+ // For testing.
3248
+ checkMaxDepth() {
3249
+ const blackDepth = this.check();
3250
+ if (Math.pow(2.0, blackDepth) <= this.size + 1) {
3251
+ return true;
3252
+ }
3253
+ else {
3254
+ return false;
3255
+ }
3256
+ }
3257
+ // In a balanced RB tree, the black-depth (number of black nodes) from root to
3258
+ // leaves is equal on both sides. This function verifies that or asserts.
3259
+ check() {
3260
+ if (this.isRed() && this.left.isRed()) {
3261
+ throw fail();
3262
+ }
3263
+ if (this.right.isRed()) {
3264
+ throw fail();
3265
+ }
3266
+ const blackDepth = this.left.check();
3267
+ if (blackDepth !== this.right.check()) {
3268
+ throw fail();
3269
+ }
3270
+ else {
3271
+ return blackDepth + (this.isRed() ? 0 : 1);
2876
3272
  }
2877
3273
  }
2878
- };
2879
- /** Extracts the backend's type order for the provided value. */
2880
- function typeOrder(value) {
2881
- if ('nullValue' in value) {
2882
- return 0 /* TypeOrder.NullValue */;
2883
- }
2884
- else if ('booleanValue' in value) {
2885
- return 1 /* TypeOrder.BooleanValue */;
2886
- }
2887
- else if ('integerValue' in value || 'doubleValue' in value) {
2888
- return 2 /* TypeOrder.NumberValue */;
3274
+ } // end LLRBNode
3275
+ // Empty node is shared between all LLRB trees.
3276
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3277
+ LLRBNode.EMPTY = null;
3278
+ LLRBNode.RED = true;
3279
+ LLRBNode.BLACK = false;
3280
+ // Represents an empty node (a leaf node in the Red-Black Tree).
3281
+ class LLRBEmptyNode {
3282
+ constructor() {
3283
+ this.size = 0;
2889
3284
  }
2890
- else if ('timestampValue' in value) {
2891
- return 3 /* TypeOrder.TimestampValue */;
3285
+ get key() {
3286
+ throw fail();
2892
3287
  }
2893
- else if ('stringValue' in value) {
2894
- return 5 /* TypeOrder.StringValue */;
3288
+ get value() {
3289
+ throw fail();
2895
3290
  }
2896
- else if ('bytesValue' in value) {
2897
- return 6 /* TypeOrder.BlobValue */;
3291
+ get color() {
3292
+ throw fail();
2898
3293
  }
2899
- else if ('referenceValue' in value) {
2900
- return 7 /* TypeOrder.RefValue */;
3294
+ get left() {
3295
+ throw fail();
2901
3296
  }
2902
- else if ('geoPointValue' in value) {
2903
- return 8 /* TypeOrder.GeoPointValue */;
3297
+ get right() {
3298
+ throw fail();
2904
3299
  }
2905
- else if ('arrayValue' in value) {
2906
- return 9 /* TypeOrder.ArrayValue */;
3300
+ // Returns a copy of the current node.
3301
+ copy(key, value, color, left, right) {
3302
+ return this;
2907
3303
  }
2908
- else if ('mapValue' in value) {
2909
- if (isServerTimestamp(value)) {
2910
- return 4 /* TypeOrder.ServerTimestampValue */;
2911
- }
2912
- else if (isMaxValue(value)) {
2913
- return 9007199254740991 /* TypeOrder.MaxValue */;
2914
- }
2915
- return 10 /* TypeOrder.ObjectValue */;
3304
+ // Returns a copy of the tree, with the specified key/value added.
3305
+ insert(key, value, comparator) {
3306
+ return new LLRBNode(key, value);
2916
3307
  }
2917
- else {
2918
- return fail();
3308
+ // Returns a copy of the tree, with the specified key removed.
3309
+ remove(key, comparator) {
3310
+ return this;
2919
3311
  }
2920
- }
2921
- /** Tests `left` and `right` for equality based on the backend semantics. */
2922
- function valueEquals(left, right) {
2923
- if (left === right) {
3312
+ isEmpty() {
2924
3313
  return true;
2925
3314
  }
2926
- const leftType = typeOrder(left);
2927
- const rightType = typeOrder(right);
2928
- if (leftType !== rightType) {
3315
+ inorderTraversal(action) {
2929
3316
  return false;
2930
3317
  }
2931
- switch (leftType) {
2932
- case 0 /* TypeOrder.NullValue */:
2933
- return true;
2934
- case 1 /* TypeOrder.BooleanValue */:
2935
- return left.booleanValue === right.booleanValue;
2936
- case 4 /* TypeOrder.ServerTimestampValue */:
2937
- return getLocalWriteTime(left).isEqual(getLocalWriteTime(right));
2938
- case 3 /* TypeOrder.TimestampValue */:
2939
- return timestampEquals(left, right);
2940
- case 5 /* TypeOrder.StringValue */:
2941
- return left.stringValue === right.stringValue;
2942
- case 6 /* TypeOrder.BlobValue */:
2943
- return blobEquals(left, right);
2944
- case 7 /* TypeOrder.RefValue */:
2945
- return left.referenceValue === right.referenceValue;
2946
- case 8 /* TypeOrder.GeoPointValue */:
2947
- return geoPointEquals(left, right);
2948
- case 2 /* TypeOrder.NumberValue */:
2949
- return numberEquals(left, right);
2950
- case 9 /* TypeOrder.ArrayValue */:
2951
- return arrayEquals(left.arrayValue.values || [], right.arrayValue.values || [], valueEquals);
2952
- case 10 /* TypeOrder.ObjectValue */:
2953
- return objectEquals(left, right);
2954
- case 9007199254740991 /* TypeOrder.MaxValue */:
2955
- return true;
2956
- default:
2957
- return fail();
2958
- }
2959
- }
2960
- function timestampEquals(left, right) {
2961
- if (typeof left.timestampValue === 'string' &&
2962
- typeof right.timestampValue === 'string' &&
2963
- left.timestampValue.length === right.timestampValue.length) {
2964
- // Use string equality for ISO 8601 timestamps
2965
- return left.timestampValue === right.timestampValue;
3318
+ reverseTraversal(action) {
3319
+ return false;
2966
3320
  }
2967
- const leftTimestamp = normalizeTimestamp(left.timestampValue);
2968
- const rightTimestamp = normalizeTimestamp(right.timestampValue);
2969
- return (leftTimestamp.seconds === rightTimestamp.seconds &&
2970
- leftTimestamp.nanos === rightTimestamp.nanos);
2971
- }
2972
- function geoPointEquals(left, right) {
2973
- return (normalizeNumber(left.geoPointValue.latitude) ===
2974
- normalizeNumber(right.geoPointValue.latitude) &&
2975
- normalizeNumber(left.geoPointValue.longitude) ===
2976
- normalizeNumber(right.geoPointValue.longitude));
2977
- }
2978
- function blobEquals(left, right) {
2979
- return normalizeByteString(left.bytesValue).isEqual(normalizeByteString(right.bytesValue));
2980
- }
2981
- function numberEquals(left, right) {
2982
- if ('integerValue' in left && 'integerValue' in right) {
2983
- return (normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue));
3321
+ minKey() {
3322
+ return null;
2984
3323
  }
2985
- else if ('doubleValue' in left && 'doubleValue' in right) {
2986
- const n1 = normalizeNumber(left.doubleValue);
2987
- const n2 = normalizeNumber(right.doubleValue);
2988
- if (n1 === n2) {
2989
- return isNegativeZero(n1) === isNegativeZero(n2);
2990
- }
2991
- else {
2992
- return isNaN(n1) && isNaN(n2);
2993
- }
3324
+ maxKey() {
3325
+ return null;
2994
3326
  }
2995
- return false;
2996
- }
2997
- function objectEquals(left, right) {
2998
- const leftMap = left.mapValue.fields || {};
2999
- const rightMap = right.mapValue.fields || {};
3000
- if (objectSize(leftMap) !== objectSize(rightMap)) {
3327
+ isRed() {
3001
3328
  return false;
3002
3329
  }
3003
- for (const key in leftMap) {
3004
- if (leftMap.hasOwnProperty(key)) {
3005
- if (rightMap[key] === undefined ||
3006
- !valueEquals(leftMap[key], rightMap[key])) {
3007
- return false;
3008
- }
3009
- }
3330
+ // For testing.
3331
+ checkMaxDepth() {
3332
+ return true;
3010
3333
  }
3011
- return true;
3012
- }
3013
- /** Returns true if the ArrayValue contains the specified element. */
3014
- function arrayValueContains(haystack, needle) {
3015
- return ((haystack.values || []).find(v => valueEquals(v, needle)) !== undefined);
3016
- }
3017
- function valueCompare(left, right) {
3018
- if (left === right) {
3334
+ check() {
3019
3335
  return 0;
3020
3336
  }
3021
- const leftType = typeOrder(left);
3022
- const rightType = typeOrder(right);
3023
- if (leftType !== rightType) {
3024
- return primitiveComparator(leftType, rightType);
3337
+ } // end LLRBEmptyNode
3338
+ LLRBNode.EMPTY = new LLRBEmptyNode();
3339
+
3340
+ /**
3341
+ * @license
3342
+ * Copyright 2017 Google LLC
3343
+ *
3344
+ * Licensed under the Apache License, Version 2.0 (the "License");
3345
+ * you may not use this file except in compliance with the License.
3346
+ * You may obtain a copy of the License at
3347
+ *
3348
+ * http://www.apache.org/licenses/LICENSE-2.0
3349
+ *
3350
+ * Unless required by applicable law or agreed to in writing, software
3351
+ * distributed under the License is distributed on an "AS IS" BASIS,
3352
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3353
+ * See the License for the specific language governing permissions and
3354
+ * limitations under the License.
3355
+ */
3356
+ /**
3357
+ * SortedSet is an immutable (copy-on-write) collection that holds elements
3358
+ * in order specified by the provided comparator.
3359
+ *
3360
+ * NOTE: if provided comparator returns 0 for two elements, we consider them to
3361
+ * be equal!
3362
+ */
3363
+ class SortedSet {
3364
+ constructor(comparator) {
3365
+ this.comparator = comparator;
3366
+ this.data = new SortedMap(this.comparator);
3025
3367
  }
3026
- switch (leftType) {
3027
- case 0 /* TypeOrder.NullValue */:
3028
- case 9007199254740991 /* TypeOrder.MaxValue */:
3029
- return 0;
3030
- case 1 /* TypeOrder.BooleanValue */:
3031
- return primitiveComparator(left.booleanValue, right.booleanValue);
3032
- case 2 /* TypeOrder.NumberValue */:
3033
- return compareNumbers(left, right);
3034
- case 3 /* TypeOrder.TimestampValue */:
3035
- return compareTimestamps(left.timestampValue, right.timestampValue);
3036
- case 4 /* TypeOrder.ServerTimestampValue */:
3037
- return compareTimestamps(getLocalWriteTime(left), getLocalWriteTime(right));
3038
- case 5 /* TypeOrder.StringValue */:
3039
- return primitiveComparator(left.stringValue, right.stringValue);
3040
- case 6 /* TypeOrder.BlobValue */:
3041
- return compareBlobs(left.bytesValue, right.bytesValue);
3042
- case 7 /* TypeOrder.RefValue */:
3043
- return compareReferences(left.referenceValue, right.referenceValue);
3044
- case 8 /* TypeOrder.GeoPointValue */:
3045
- return compareGeoPoints(left.geoPointValue, right.geoPointValue);
3046
- case 9 /* TypeOrder.ArrayValue */:
3047
- return compareArrays(left.arrayValue, right.arrayValue);
3048
- case 10 /* TypeOrder.ObjectValue */:
3049
- return compareMaps(left.mapValue, right.mapValue);
3050
- default:
3051
- throw fail();
3368
+ has(elem) {
3369
+ return this.data.get(elem) !== null;
3052
3370
  }
3053
- }
3054
- function compareNumbers(left, right) {
3055
- const leftNumber = normalizeNumber(left.integerValue || left.doubleValue);
3056
- const rightNumber = normalizeNumber(right.integerValue || right.doubleValue);
3057
- if (leftNumber < rightNumber) {
3058
- return -1;
3371
+ first() {
3372
+ return this.data.minKey();
3059
3373
  }
3060
- else if (leftNumber > rightNumber) {
3061
- return 1;
3374
+ last() {
3375
+ return this.data.maxKey();
3062
3376
  }
3063
- else if (leftNumber === rightNumber) {
3064
- return 0;
3377
+ get size() {
3378
+ return this.data.size;
3379
+ }
3380
+ indexOf(elem) {
3381
+ return this.data.indexOf(elem);
3382
+ }
3383
+ /** Iterates elements in order defined by "comparator" */
3384
+ forEach(cb) {
3385
+ this.data.inorderTraversal((k, v) => {
3386
+ cb(k);
3387
+ return false;
3388
+ });
3389
+ }
3390
+ /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
3391
+ forEachInRange(range, cb) {
3392
+ const iter = this.data.getIteratorFrom(range[0]);
3393
+ while (iter.hasNext()) {
3394
+ const elem = iter.getNext();
3395
+ if (this.comparator(elem.key, range[1]) >= 0) {
3396
+ return;
3397
+ }
3398
+ cb(elem.key);
3399
+ }
3065
3400
  }
3066
- else {
3067
- // one or both are NaN.
3068
- if (isNaN(leftNumber)) {
3069
- return isNaN(rightNumber) ? 0 : -1;
3401
+ /**
3402
+ * Iterates over `elem`s such that: start &lt;= elem until false is returned.
3403
+ */
3404
+ forEachWhile(cb, start) {
3405
+ let iter;
3406
+ if (start !== undefined) {
3407
+ iter = this.data.getIteratorFrom(start);
3070
3408
  }
3071
3409
  else {
3072
- return 1;
3410
+ iter = this.data.getIterator();
3411
+ }
3412
+ while (iter.hasNext()) {
3413
+ const elem = iter.getNext();
3414
+ const result = cb(elem.key);
3415
+ if (!result) {
3416
+ return;
3417
+ }
3073
3418
  }
3074
3419
  }
3075
- }
3076
- function compareTimestamps(left, right) {
3077
- if (typeof left === 'string' &&
3078
- typeof right === 'string' &&
3079
- left.length === right.length) {
3080
- return primitiveComparator(left, right);
3420
+ /** Finds the least element greater than or equal to `elem`. */
3421
+ firstAfterOrEqual(elem) {
3422
+ const iter = this.data.getIteratorFrom(elem);
3423
+ return iter.hasNext() ? iter.getNext().key : null;
3081
3424
  }
3082
- const leftTimestamp = normalizeTimestamp(left);
3083
- const rightTimestamp = normalizeTimestamp(right);
3084
- const comparison = primitiveComparator(leftTimestamp.seconds, rightTimestamp.seconds);
3085
- if (comparison !== 0) {
3086
- return comparison;
3425
+ getIterator() {
3426
+ return new SortedSetIterator(this.data.getIterator());
3087
3427
  }
3088
- return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos);
3089
- }
3090
- function compareReferences(leftPath, rightPath) {
3091
- const leftSegments = leftPath.split('/');
3092
- const rightSegments = rightPath.split('/');
3093
- for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) {
3094
- const comparison = primitiveComparator(leftSegments[i], rightSegments[i]);
3095
- if (comparison !== 0) {
3096
- return comparison;
3097
- }
3428
+ getIteratorFrom(key) {
3429
+ return new SortedSetIterator(this.data.getIteratorFrom(key));
3098
3430
  }
3099
- return primitiveComparator(leftSegments.length, rightSegments.length);
3100
- }
3101
- function compareGeoPoints(left, right) {
3102
- const comparison = primitiveComparator(normalizeNumber(left.latitude), normalizeNumber(right.latitude));
3103
- if (comparison !== 0) {
3104
- return comparison;
3431
+ /** Inserts or updates an element */
3432
+ add(elem) {
3433
+ return this.copy(this.data.remove(elem).insert(elem, true));
3105
3434
  }
3106
- return primitiveComparator(normalizeNumber(left.longitude), normalizeNumber(right.longitude));
3107
- }
3108
- function compareBlobs(left, right) {
3109
- const leftBytes = normalizeByteString(left);
3110
- const rightBytes = normalizeByteString(right);
3111
- return leftBytes.compareTo(rightBytes);
3112
- }
3113
- function compareArrays(left, right) {
3114
- const leftArray = left.values || [];
3115
- const rightArray = right.values || [];
3116
- for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) {
3117
- const compare = valueCompare(leftArray[i], rightArray[i]);
3118
- if (compare) {
3119
- return compare;
3435
+ /** Deletes an element */
3436
+ delete(elem) {
3437
+ if (!this.has(elem)) {
3438
+ return this;
3120
3439
  }
3440
+ return this.copy(this.data.remove(elem));
3121
3441
  }
3122
- return primitiveComparator(leftArray.length, rightArray.length);
3123
- }
3124
- function compareMaps(left, right) {
3125
- if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) {
3126
- return 0;
3127
- }
3128
- else if (left === MAX_VALUE.mapValue) {
3129
- return 1;
3442
+ isEmpty() {
3443
+ return this.data.isEmpty();
3130
3444
  }
3131
- else if (right === MAX_VALUE.mapValue) {
3132
- return -1;
3445
+ unionWith(other) {
3446
+ let result = this;
3447
+ // Make sure `result` always refers to the larger one of the two sets.
3448
+ if (result.size < other.size) {
3449
+ result = other;
3450
+ other = this;
3451
+ }
3452
+ other.forEach(elem => {
3453
+ result = result.add(elem);
3454
+ });
3455
+ return result;
3133
3456
  }
3134
- const leftMap = left.fields || {};
3135
- const leftKeys = Object.keys(leftMap);
3136
- const rightMap = right.fields || {};
3137
- const rightKeys = Object.keys(rightMap);
3138
- // Even though MapValues are likely sorted correctly based on their insertion
3139
- // order (e.g. when received from the backend), local modifications can bring
3140
- // elements out of order. We need to re-sort the elements to ensure that
3141
- // canonical IDs are independent of insertion order.
3142
- leftKeys.sort();
3143
- rightKeys.sort();
3144
- for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) {
3145
- const keyCompare = primitiveComparator(leftKeys[i], rightKeys[i]);
3146
- if (keyCompare !== 0) {
3147
- return keyCompare;
3457
+ isEqual(other) {
3458
+ if (!(other instanceof SortedSet)) {
3459
+ return false;
3148
3460
  }
3149
- const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]);
3150
- if (compare !== 0) {
3151
- return compare;
3461
+ if (this.size !== other.size) {
3462
+ return false;
3463
+ }
3464
+ const thisIt = this.data.getIterator();
3465
+ const otherIt = other.data.getIterator();
3466
+ while (thisIt.hasNext()) {
3467
+ const thisElem = thisIt.getNext().key;
3468
+ const otherElem = otherIt.getNext().key;
3469
+ if (this.comparator(thisElem, otherElem) !== 0) {
3470
+ return false;
3471
+ }
3152
3472
  }
3473
+ return true;
3474
+ }
3475
+ toArray() {
3476
+ const res = [];
3477
+ this.forEach(targetId => {
3478
+ res.push(targetId);
3479
+ });
3480
+ return res;
3481
+ }
3482
+ toString() {
3483
+ const result = [];
3484
+ this.forEach(elem => result.push(elem));
3485
+ return 'SortedSet(' + result.toString() + ')';
3486
+ }
3487
+ copy(data) {
3488
+ const result = new SortedSet(this.comparator);
3489
+ result.data = data;
3490
+ return result;
3153
3491
  }
3154
- return primitiveComparator(leftKeys.length, rightKeys.length);
3155
- }
3156
- /** Returns a reference value for the provided database and key. */
3157
- function refValue(databaseId, key) {
3158
- return {
3159
- referenceValue: `projects/${databaseId.projectId}/databases/${databaseId.database}/documents/${key.path.canonicalString()}`
3160
- };
3161
- }
3162
- /** Returns true if `value` is an ArrayValue. */
3163
- function isArray(value) {
3164
- return !!value && 'arrayValue' in value;
3165
- }
3166
- /** Returns true if `value` is a NullValue. */
3167
- function isNullValue(value) {
3168
- return !!value && 'nullValue' in value;
3169
- }
3170
- /** Returns true if `value` is NaN. */
3171
- function isNanValue(value) {
3172
- return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue));
3173
- }
3174
- /** Returns true if `value` is a MapValue. */
3175
- function isMapValue(value) {
3176
- return !!value && 'mapValue' in value;
3177
3492
  }
3178
- /** Creates a deep copy of `source`. */
3179
- function deepClone(source) {
3180
- if (source.geoPointValue) {
3181
- return { geoPointValue: Object.assign({}, source.geoPointValue) };
3493
+ class SortedSetIterator {
3494
+ constructor(iter) {
3495
+ this.iter = iter;
3182
3496
  }
3183
- else if (source.timestampValue &&
3184
- typeof source.timestampValue === 'object') {
3185
- return { timestampValue: Object.assign({}, source.timestampValue) };
3497
+ getNext() {
3498
+ return this.iter.getNext().key;
3186
3499
  }
3187
- else if (source.mapValue) {
3188
- const target = { mapValue: { fields: {} } };
3189
- forEach(source.mapValue.fields, (key, val) => (target.mapValue.fields[key] = deepClone(val)));
3190
- return target;
3500
+ hasNext() {
3501
+ return this.iter.hasNext();
3191
3502
  }
3192
- else if (source.arrayValue) {
3193
- const target = { arrayValue: { values: [] } };
3194
- for (let i = 0; i < (source.arrayValue.values || []).length; ++i) {
3195
- target.arrayValue.values[i] = deepClone(source.arrayValue.values[i]);
3503
+ }
3504
+
3505
+ /**
3506
+ * @license
3507
+ * Copyright 2020 Google LLC
3508
+ *
3509
+ * Licensed under the Apache License, Version 2.0 (the "License");
3510
+ * you may not use this file except in compliance with the License.
3511
+ * You may obtain a copy of the License at
3512
+ *
3513
+ * http://www.apache.org/licenses/LICENSE-2.0
3514
+ *
3515
+ * Unless required by applicable law or agreed to in writing, software
3516
+ * distributed under the License is distributed on an "AS IS" BASIS,
3517
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3518
+ * See the License for the specific language governing permissions and
3519
+ * limitations under the License.
3520
+ */
3521
+ /**
3522
+ * Provides a set of fields that can be used to partially patch a document.
3523
+ * FieldMask is used in conjunction with ObjectValue.
3524
+ * Examples:
3525
+ * foo - Overwrites foo entirely with the provided value. If foo is not
3526
+ * present in the companion ObjectValue, the field is deleted.
3527
+ * foo.bar - Overwrites only the field bar of the object foo.
3528
+ * If foo is not an object, foo is replaced with an object
3529
+ * containing foo
3530
+ */
3531
+ class FieldMask {
3532
+ constructor(fields) {
3533
+ this.fields = fields;
3534
+ // TODO(dimond): validation of FieldMask
3535
+ // Sort the field mask to support `FieldMask.isEqual()` and assert below.
3536
+ fields.sort(FieldPath$1.comparator);
3537
+ }
3538
+ static empty() {
3539
+ return new FieldMask([]);
3540
+ }
3541
+ /**
3542
+ * Returns a new FieldMask object that is the result of adding all the given
3543
+ * fields paths to this field mask.
3544
+ */
3545
+ unionWith(extraFields) {
3546
+ let mergedMaskSet = new SortedSet(FieldPath$1.comparator);
3547
+ for (const fieldPath of this.fields) {
3548
+ mergedMaskSet = mergedMaskSet.add(fieldPath);
3549
+ }
3550
+ for (const fieldPath of extraFields) {
3551
+ mergedMaskSet = mergedMaskSet.add(fieldPath);
3552
+ }
3553
+ return new FieldMask(mergedMaskSet.toArray());
3554
+ }
3555
+ /**
3556
+ * Verifies that `fieldPath` is included by at least one field in this field
3557
+ * mask.
3558
+ *
3559
+ * This is an O(n) operation, where `n` is the size of the field mask.
3560
+ */
3561
+ covers(fieldPath) {
3562
+ for (const fieldMaskPath of this.fields) {
3563
+ if (fieldMaskPath.isPrefixOf(fieldPath)) {
3564
+ return true;
3565
+ }
3196
3566
  }
3197
- return target;
3567
+ return false;
3198
3568
  }
3199
- else {
3200
- return Object.assign({}, source);
3569
+ isEqual(other) {
3570
+ return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r));
3201
3571
  }
3202
- }
3203
- /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */
3204
- function isMaxValue(value) {
3205
- return ((((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue ===
3206
- MAX_VALUE_TYPE);
3207
3572
  }
3208
3573
 
3209
3574
  /**
@@ -3453,335 +3818,112 @@ class MutableDocument {
3453
3818
  get hasLocalMutations() {
3454
3819
  return this.documentState === 1 /* DocumentState.HAS_LOCAL_MUTATIONS */;
3455
3820
  }
3456
- get hasCommittedMutations() {
3457
- return this.documentState === 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */;
3458
- }
3459
- get hasPendingWrites() {
3460
- return this.hasLocalMutations || this.hasCommittedMutations;
3461
- }
3462
- isValidDocument() {
3463
- return this.documentType !== 0 /* DocumentType.INVALID */;
3464
- }
3465
- isFoundDocument() {
3466
- return this.documentType === 1 /* DocumentType.FOUND_DOCUMENT */;
3467
- }
3468
- isNoDocument() {
3469
- return this.documentType === 2 /* DocumentType.NO_DOCUMENT */;
3470
- }
3471
- isUnknownDocument() {
3472
- return this.documentType === 3 /* DocumentType.UNKNOWN_DOCUMENT */;
3473
- }
3474
- isEqual(other) {
3475
- return (other instanceof MutableDocument &&
3476
- this.key.isEqual(other.key) &&
3477
- this.version.isEqual(other.version) &&
3478
- this.documentType === other.documentType &&
3479
- this.documentState === other.documentState &&
3480
- this.data.isEqual(other.data));
3481
- }
3482
- mutableCopy() {
3483
- return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.data.clone(), this.documentState);
3484
- }
3485
- toString() {
3486
- return (`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, ` +
3487
- `{documentType: ${this.documentType}}), ` +
3488
- `{documentState: ${this.documentState}})`);
3489
- }
3490
- }
3491
-
3492
- /**
3493
- * @license
3494
- * Copyright 2019 Google LLC
3495
- *
3496
- * Licensed under the Apache License, Version 2.0 (the "License");
3497
- * you may not use this file except in compliance with the License.
3498
- * You may obtain a copy of the License at
3499
- *
3500
- * http://www.apache.org/licenses/LICENSE-2.0
3501
- *
3502
- * Unless required by applicable law or agreed to in writing, software
3503
- * distributed under the License is distributed on an "AS IS" BASIS,
3504
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3505
- * See the License for the specific language governing permissions and
3506
- * limitations under the License.
3507
- */
3508
- // Visible for testing
3509
- class TargetImpl {
3510
- constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
3511
- this.path = path;
3512
- this.collectionGroup = collectionGroup;
3513
- this.orderBy = orderBy;
3514
- this.filters = filters;
3515
- this.limit = limit;
3516
- this.startAt = startAt;
3517
- this.endAt = endAt;
3518
- this.memoizedCanonicalId = null;
3519
- }
3520
- }
3521
- /**
3522
- * Initializes a Target with a path and optional additional query constraints.
3523
- * Path must currently be empty if this is a collection group query.
3524
- *
3525
- * NOTE: you should always construct `Target` from `Query.toTarget` instead of
3526
- * using this factory method, because `Query` provides an implicit `orderBy`
3527
- * property.
3528
- */
3529
- function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
3530
- return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt);
3531
- }
3532
- function targetEquals(left, right) {
3533
- if (left.limit !== right.limit) {
3534
- return false;
3535
- }
3536
- if (left.orderBy.length !== right.orderBy.length) {
3537
- return false;
3538
- }
3539
- for (let i = 0; i < left.orderBy.length; i++) {
3540
- if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {
3541
- return false;
3542
- }
3543
- }
3544
- if (left.filters.length !== right.filters.length) {
3545
- return false;
3546
- }
3547
- for (let i = 0; i < left.filters.length; i++) {
3548
- if (!filterEquals(left.filters[i], right.filters[i])) {
3549
- return false;
3550
- }
3551
- }
3552
- if (left.collectionGroup !== right.collectionGroup) {
3553
- return false;
3554
- }
3555
- if (!left.path.isEqual(right.path)) {
3556
- return false;
3557
- }
3558
- if (!boundEquals(left.startAt, right.startAt)) {
3559
- return false;
3560
- }
3561
- return boundEquals(left.endAt, right.endAt);
3562
- }
3563
- class Filter {
3564
- }
3565
- class FieldFilter extends Filter {
3566
- constructor(field, op, value) {
3567
- super();
3568
- this.field = field;
3569
- this.op = op;
3570
- this.value = value;
3571
- }
3572
- /**
3573
- * Creates a filter based on the provided arguments.
3574
- */
3575
- static create(field, op, value) {
3576
- if (field.isKeyField()) {
3577
- if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) {
3578
- return this.createKeyFieldInFilter(field, op, value);
3579
- }
3580
- else {
3581
- return new KeyFieldFilter(field, op, value);
3582
- }
3583
- }
3584
- else if (op === "array-contains" /* Operator.ARRAY_CONTAINS */) {
3585
- return new ArrayContainsFilter(field, value);
3586
- }
3587
- else if (op === "in" /* Operator.IN */) {
3588
- return new InFilter(field, value);
3589
- }
3590
- else if (op === "not-in" /* Operator.NOT_IN */) {
3591
- return new NotInFilter(field, value);
3592
- }
3593
- else if (op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) {
3594
- return new ArrayContainsAnyFilter(field, value);
3595
- }
3596
- else {
3597
- return new FieldFilter(field, op, value);
3598
- }
3599
- }
3600
- static createKeyFieldInFilter(field, op, value) {
3601
- return op === "in" /* Operator.IN */
3602
- ? new KeyFieldInFilter(field, value)
3603
- : new KeyFieldNotInFilter(field, value);
3604
- }
3605
- matches(doc) {
3606
- const other = doc.data.field(this.field);
3607
- // Types do not have to match in NOT_EQUAL filters.
3608
- if (this.op === "!=" /* Operator.NOT_EQUAL */) {
3609
- return (other !== null &&
3610
- this.matchesComparison(valueCompare(other, this.value)));
3611
- }
3612
- // Only compare types with matching backend order (such as double and int).
3613
- return (other !== null &&
3614
- typeOrder(this.value) === typeOrder(other) &&
3615
- this.matchesComparison(valueCompare(other, this.value)));
3616
- }
3617
- matchesComparison(comparison) {
3618
- switch (this.op) {
3619
- case "<" /* Operator.LESS_THAN */:
3620
- return comparison < 0;
3621
- case "<=" /* Operator.LESS_THAN_OR_EQUAL */:
3622
- return comparison <= 0;
3623
- case "==" /* Operator.EQUAL */:
3624
- return comparison === 0;
3625
- case "!=" /* Operator.NOT_EQUAL */:
3626
- return comparison !== 0;
3627
- case ">" /* Operator.GREATER_THAN */:
3628
- return comparison > 0;
3629
- case ">=" /* Operator.GREATER_THAN_OR_EQUAL */:
3630
- return comparison >= 0;
3631
- default:
3632
- return fail();
3633
- }
3634
- }
3635
- isInequality() {
3636
- return ([
3637
- "<" /* Operator.LESS_THAN */,
3638
- "<=" /* Operator.LESS_THAN_OR_EQUAL */,
3639
- ">" /* Operator.GREATER_THAN */,
3640
- ">=" /* Operator.GREATER_THAN_OR_EQUAL */,
3641
- "!=" /* Operator.NOT_EQUAL */,
3642
- "not-in" /* Operator.NOT_IN */
3643
- ].indexOf(this.op) >= 0);
3644
- }
3645
- }
3646
- function filterEquals(f1, f2) {
3647
- return (f1.op === f2.op &&
3648
- f1.field.isEqual(f2.field) &&
3649
- valueEquals(f1.value, f2.value));
3650
- }
3651
- /** Filter that matches on key fields (i.e. '__name__'). */
3652
- class KeyFieldFilter extends FieldFilter {
3653
- constructor(field, op, value) {
3654
- super(field, op, value);
3655
- this.key = DocumentKey.fromName(value.referenceValue);
3656
- }
3657
- matches(doc) {
3658
- const comparison = DocumentKey.comparator(doc.key, this.key);
3659
- return this.matchesComparison(comparison);
3660
- }
3661
- }
3662
- /** Filter that matches on key fields within an array. */
3663
- class KeyFieldInFilter extends FieldFilter {
3664
- constructor(field, value) {
3665
- super(field, "in" /* Operator.IN */, value);
3666
- this.keys = extractDocumentKeysFromArrayValue("in" /* Operator.IN */, value);
3667
- }
3668
- matches(doc) {
3669
- return this.keys.some(key => key.isEqual(doc.key));
3670
- }
3671
- }
3672
- /** Filter that matches on key fields not present within an array. */
3673
- class KeyFieldNotInFilter extends FieldFilter {
3674
- constructor(field, value) {
3675
- super(field, "not-in" /* Operator.NOT_IN */, value);
3676
- this.keys = extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */, value);
3677
- }
3678
- matches(doc) {
3679
- return !this.keys.some(key => key.isEqual(doc.key));
3680
- }
3681
- }
3682
- function extractDocumentKeysFromArrayValue(op, value) {
3683
- var _a;
3684
- return (((_a = value.arrayValue) === null || _a === void 0 ? void 0 : _a.values) || []).map(v => {
3685
- return DocumentKey.fromName(v.referenceValue);
3686
- });
3687
- }
3688
- /** A Filter that implements the array-contains operator. */
3689
- class ArrayContainsFilter extends FieldFilter {
3690
- constructor(field, value) {
3691
- super(field, "array-contains" /* Operator.ARRAY_CONTAINS */, value);
3692
- }
3693
- matches(doc) {
3694
- const other = doc.data.field(this.field);
3695
- return isArray(other) && arrayValueContains(other.arrayValue, this.value);
3821
+ get hasCommittedMutations() {
3822
+ return this.documentState === 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */;
3696
3823
  }
3697
- }
3698
- /** A Filter that implements the IN operator. */
3699
- class InFilter extends FieldFilter {
3700
- constructor(field, value) {
3701
- super(field, "in" /* Operator.IN */, value);
3824
+ get hasPendingWrites() {
3825
+ return this.hasLocalMutations || this.hasCommittedMutations;
3702
3826
  }
3703
- matches(doc) {
3704
- const other = doc.data.field(this.field);
3705
- return other !== null && arrayValueContains(this.value.arrayValue, other);
3827
+ isValidDocument() {
3828
+ return this.documentType !== 0 /* DocumentType.INVALID */;
3706
3829
  }
3707
- }
3708
- /** A Filter that implements the not-in operator. */
3709
- class NotInFilter extends FieldFilter {
3710
- constructor(field, value) {
3711
- super(field, "not-in" /* Operator.NOT_IN */, value);
3830
+ isFoundDocument() {
3831
+ return this.documentType === 1 /* DocumentType.FOUND_DOCUMENT */;
3712
3832
  }
3713
- matches(doc) {
3714
- if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) {
3715
- return false;
3716
- }
3717
- const other = doc.data.field(this.field);
3718
- return other !== null && !arrayValueContains(this.value.arrayValue, other);
3833
+ isNoDocument() {
3834
+ return this.documentType === 2 /* DocumentType.NO_DOCUMENT */;
3719
3835
  }
3720
- }
3721
- /** A Filter that implements the array-contains-any operator. */
3722
- class ArrayContainsAnyFilter extends FieldFilter {
3723
- constructor(field, value) {
3724
- super(field, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, value);
3836
+ isUnknownDocument() {
3837
+ return this.documentType === 3 /* DocumentType.UNKNOWN_DOCUMENT */;
3725
3838
  }
3726
- matches(doc) {
3727
- const other = doc.data.field(this.field);
3728
- if (!isArray(other) || !other.arrayValue.values) {
3729
- return false;
3730
- }
3731
- return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val));
3839
+ isEqual(other) {
3840
+ return (other instanceof MutableDocument &&
3841
+ this.key.isEqual(other.key) &&
3842
+ this.version.isEqual(other.version) &&
3843
+ this.documentType === other.documentType &&
3844
+ this.documentState === other.documentState &&
3845
+ this.data.isEqual(other.data));
3732
3846
  }
3733
- }
3847
+ mutableCopy() {
3848
+ return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.data.clone(), this.documentState);
3849
+ }
3850
+ toString() {
3851
+ return (`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, ` +
3852
+ `{documentType: ${this.documentType}}), ` +
3853
+ `{documentState: ${this.documentState}})`);
3854
+ }
3855
+ }
3856
+
3734
3857
  /**
3735
- * Represents a bound of a query.
3858
+ * @license
3859
+ * Copyright 2019 Google LLC
3736
3860
  *
3737
- * The bound is specified with the given components representing a position and
3738
- * whether it's just before or just after the position (relative to whatever the
3739
- * query order is).
3861
+ * Licensed under the Apache License, Version 2.0 (the "License");
3862
+ * you may not use this file except in compliance with the License.
3863
+ * You may obtain a copy of the License at
3740
3864
  *
3741
- * The position represents a logical index position for a query. It's a prefix
3742
- * of values for the (potentially implicit) order by clauses of a query.
3865
+ * http://www.apache.org/licenses/LICENSE-2.0
3743
3866
  *
3744
- * Bound provides a function to determine whether a document comes before or
3745
- * after a bound. This is influenced by whether the position is just before or
3746
- * just after the provided values.
3867
+ * Unless required by applicable law or agreed to in writing, software
3868
+ * distributed under the License is distributed on an "AS IS" BASIS,
3869
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3870
+ * See the License for the specific language governing permissions and
3871
+ * limitations under the License.
3747
3872
  */
3748
- class Bound {
3749
- constructor(position, inclusive) {
3750
- this.position = position;
3751
- this.inclusive = inclusive;
3873
+ // Visible for testing
3874
+ class TargetImpl {
3875
+ constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
3876
+ this.path = path;
3877
+ this.collectionGroup = collectionGroup;
3878
+ this.orderBy = orderBy;
3879
+ this.filters = filters;
3880
+ this.limit = limit;
3881
+ this.startAt = startAt;
3882
+ this.endAt = endAt;
3883
+ this.memoizedCanonicalId = null;
3752
3884
  }
3753
3885
  }
3754
3886
  /**
3755
- * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
3887
+ * Initializes a Target with a path and optional additional query constraints.
3888
+ * Path must currently be empty if this is a collection group query.
3889
+ *
3890
+ * NOTE: you should always construct `Target` from `Query.toTarget` instead of
3891
+ * using this factory method, because `Query` provides an implicit `orderBy`
3892
+ * property.
3756
3893
  */
3757
- class OrderBy {
3758
- constructor(field, dir = "asc" /* Direction.ASCENDING */) {
3759
- this.field = field;
3760
- this.dir = dir;
3761
- }
3762
- }
3763
- function orderByEquals(left, right) {
3764
- return left.dir === right.dir && left.field.isEqual(right.field);
3894
+ function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
3895
+ return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt);
3765
3896
  }
3766
- function boundEquals(left, right) {
3767
- if (left === null) {
3768
- return right === null;
3897
+ function targetEquals(left, right) {
3898
+ if (left.limit !== right.limit) {
3899
+ return false;
3769
3900
  }
3770
- else if (right === null) {
3901
+ if (left.orderBy.length !== right.orderBy.length) {
3771
3902
  return false;
3772
3903
  }
3773
- if (left.inclusive !== right.inclusive ||
3774
- left.position.length !== right.position.length) {
3904
+ for (let i = 0; i < left.orderBy.length; i++) {
3905
+ if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {
3906
+ return false;
3907
+ }
3908
+ }
3909
+ if (left.filters.length !== right.filters.length) {
3775
3910
  return false;
3776
3911
  }
3777
- for (let i = 0; i < left.position.length; i++) {
3778
- const leftPosition = left.position[i];
3779
- const rightPosition = right.position[i];
3780
- if (!valueEquals(leftPosition, rightPosition)) {
3912
+ for (let i = 0; i < left.filters.length; i++) {
3913
+ if (!filterEquals(left.filters[i], right.filters[i])) {
3781
3914
  return false;
3782
3915
  }
3783
3916
  }
3784
- return true;
3917
+ if (left.collectionGroup !== right.collectionGroup) {
3918
+ return false;
3919
+ }
3920
+ if (!left.path.isEqual(right.path)) {
3921
+ return false;
3922
+ }
3923
+ if (!boundEquals(left.startAt, right.startAt)) {
3924
+ return false;
3925
+ }
3926
+ return boundEquals(left.endAt, right.endAt);
3785
3927
  }
3786
3928
 
3787
3929
  /**
@@ -3839,20 +3981,9 @@ function getFirstOrderByField(query) {
3839
3981
  }
3840
3982
  function getInequalityFilterField(query) {
3841
3983
  for (const filter of query.filters) {
3842
- if (filter.isInequality()) {
3843
- return filter.field;
3844
- }
3845
- }
3846
- return null;
3847
- }
3848
- /**
3849
- * Checks if any of the provided Operators are included in the query and
3850
- * returns the first one that is, or null if none are.
3851
- */
3852
- function findFilterOperator(query, operators) {
3853
- for (const filter of query.filters) {
3854
- if (operators.indexOf(filter.op) >= 0) {
3855
- return filter.op;
3984
+ const result = filter.getFirstInequalityField();
3985
+ if (result !== null) {
3986
+ return result;
3856
3987
  }
3857
3988
  }
3858
3989
  return null;
@@ -3944,6 +4075,8 @@ function queryToTarget(query) {
3944
4075
  return queryImpl.memoizedTarget;
3945
4076
  }
3946
4077
  function queryWithAddedFilter(query, filter) {
4078
+ filter.getFirstInequalityField();
4079
+ getInequalityFilterField(query);
3947
4080
  const newFilters = query.filters.concat([filter]);
3948
4081
  return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt);
3949
4082
  }
@@ -4285,6 +4418,12 @@ const OPERATORS = (() => {
4285
4418
  ops["array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */] = 'ARRAY_CONTAINS_ANY';
4286
4419
  return ops;
4287
4420
  })();
4421
+ const COMPOSITE_OPERATORS = (() => {
4422
+ const ops = {};
4423
+ ops["and" /* CompositeOperator.AND */] = 'AND';
4424
+ ops["or" /* CompositeOperator.OR */] = 'OR';
4425
+ return ops;
4426
+ })();
4288
4427
  function assertPresent(value, description) {
4289
4428
  }
4290
4429
  /**
@@ -4562,7 +4701,7 @@ function toQueryTarget(serializer, target) {
4562
4701
  result.parent = toQueryPath(serializer, path.popLast());
4563
4702
  result.structuredQuery.from = [{ collectionId: path.lastSegment() }];
4564
4703
  }
4565
- const where = toFilter(target.filters);
4704
+ const where = toFilters(target.filters);
4566
4705
  if (where) {
4567
4706
  result.structuredQuery.where = where;
4568
4707
  }
@@ -4597,17 +4736,11 @@ function toRunAggregationQueryRequest(serializer, target) {
4597
4736
  parent: queryTarget.parent
4598
4737
  };
4599
4738
  }
4600
- function toFilter(filters) {
4739
+ function toFilters(filters) {
4601
4740
  if (filters.length === 0) {
4602
4741
  return;
4603
4742
  }
4604
- const protos = filters.map(filter => {
4605
- return toUnaryOrFieldFilter(filter);
4606
- });
4607
- if (protos.length === 1) {
4608
- return protos[0];
4609
- }
4610
- return { compositeFilter: { op: 'AND', filters: protos } };
4743
+ return toFilter(CompositeFilter.create(filters, "and" /* CompositeOperator.AND */));
4611
4744
  }
4612
4745
  function toOrder(orderBys) {
4613
4746
  if (orderBys.length === 0) {
@@ -4635,6 +4768,9 @@ function toDirection(dir) {
4635
4768
  function toOperatorName(op) {
4636
4769
  return OPERATORS[op];
4637
4770
  }
4771
+ function toCompositeOperatorName(op) {
4772
+ return COMPOSITE_OPERATORS[op];
4773
+ }
4638
4774
  function toFieldPathReference(path) {
4639
4775
  return { fieldPath: path.canonicalString() };
4640
4776
  }
@@ -4646,6 +4782,29 @@ function toPropertyOrder(orderBy) {
4646
4782
  };
4647
4783
  }
4648
4784
  // visible for testing
4785
+ function toFilter(filter) {
4786
+ if (filter instanceof FieldFilter) {
4787
+ return toUnaryOrFieldFilter(filter);
4788
+ }
4789
+ else if (filter instanceof CompositeFilter) {
4790
+ return toCompositeFilter(filter);
4791
+ }
4792
+ else {
4793
+ return fail();
4794
+ }
4795
+ }
4796
+ function toCompositeFilter(filter) {
4797
+ const protos = filter.getFilters().map(filter => toFilter(filter));
4798
+ if (protos.length === 1) {
4799
+ return protos[0];
4800
+ }
4801
+ return {
4802
+ compositeFilter: {
4803
+ op: toCompositeOperatorName(filter.op),
4804
+ filters: protos
4805
+ }
4806
+ };
4807
+ }
4649
4808
  function toUnaryOrFieldFilter(filter) {
4650
4809
  if (filter.op === "==" /* Operator.EQUAL */) {
4651
4810
  if (isNanValue(filter.value)) {
@@ -6880,159 +7039,329 @@ function validateHasExplicitOrderByForLimitToLast(query) {
6880
7039
  throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause');
6881
7040
  }
6882
7041
  }
7042
+ /**
7043
+ * An `AppliableConstraint` is an abstraction of a constraint that can be applied
7044
+ * to a Firestore query.
7045
+ */
7046
+ class AppliableConstraint {
7047
+ }
6883
7048
  /**
6884
7049
  * A `QueryConstraint` is used to narrow the set of documents returned by a
6885
7050
  * Firestore query. `QueryConstraint`s are created by invoking {@link where},
6886
- * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link
6887
- * endBefore:1}, {@link (endAt:1)}, {@link limit} or {@link limitToLast} and
7051
+ * {@link orderBy}, {@link startAt}, {@link startAfter}, {@link
7052
+ * endBefore}, {@link endAt}, {@link limit}, {@link limitToLast} and
6888
7053
  * can then be passed to {@link query} to create a new query instance that
6889
7054
  * also contains this `QueryConstraint`.
6890
7055
  */
6891
- class QueryConstraint {
7056
+ class QueryConstraint extends AppliableConstraint {
6892
7057
  }
6893
- /**
6894
- * Creates a new immutable instance of {@link Query} that is extended to also include
6895
- * additional query constraints.
6896
- *
6897
- * @param query - The {@link Query} instance to use as a base for the new constraints.
6898
- * @param queryConstraints - The list of {@link QueryConstraint}s to apply.
6899
- * @throws if any of the provided query constraints cannot be combined with the
6900
- * existing or new constraints.
6901
- */
6902
- function query(query, ...queryConstraints) {
7058
+ function query(query, queryConstraint, ...additionalQueryConstraints) {
7059
+ let queryConstraints = [];
7060
+ if (queryConstraint instanceof AppliableConstraint) {
7061
+ queryConstraints.push(queryConstraint);
7062
+ }
7063
+ queryConstraints = queryConstraints.concat(additionalQueryConstraints);
7064
+ validateQueryConstraintArray(queryConstraints);
6903
7065
  for (const constraint of queryConstraints) {
6904
7066
  query = constraint._apply(query);
6905
7067
  }
6906
7068
  return query;
6907
7069
  }
6908
- class QueryFilterConstraint extends QueryConstraint {
7070
+ /**
7071
+ * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
7072
+ * a Firestore query by filtering on one or more document fields.
7073
+ * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
7074
+ * be passed to {@link query} to create a new query instance that also contains
7075
+ * this `QueryFieldFilterConstraint`.
7076
+ */
7077
+ class QueryFieldFilterConstraint extends QueryConstraint {
7078
+ /**
7079
+ * @internal
7080
+ */
6909
7081
  constructor(_field, _op, _value) {
6910
7082
  super();
6911
7083
  this._field = _field;
6912
7084
  this._op = _op;
6913
7085
  this._value = _value;
7086
+ /** The type of this query constraint */
6914
7087
  this.type = 'where';
6915
7088
  }
7089
+ static _create(_field, _op, _value) {
7090
+ return new QueryFieldFilterConstraint(_field, _op, _value);
7091
+ }
6916
7092
  _apply(query) {
7093
+ const filter = this._parse(query);
7094
+ validateNewFieldFilter(query._query, filter);
7095
+ return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter));
7096
+ }
7097
+ _parse(query) {
6917
7098
  const reader = newUserDataReader(query.firestore);
6918
7099
  const filter = newQueryFilter(query._query, 'where', reader, query.firestore._databaseId, this._field, this._op, this._value);
6919
- return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter));
7100
+ return filter;
6920
7101
  }
6921
7102
  }
6922
7103
  /**
6923
- * Creates a {@link QueryConstraint} that enforces that documents must contain the
6924
- * specified field and that the value should satisfy the relation constraint
6925
- * provided.
7104
+ * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
7105
+ * must contain the specified field and that the value should satisfy the
7106
+ * relation constraint provided.
6926
7107
  *
6927
7108
  * @param fieldPath - The path to compare
6928
7109
  * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
6929
7110
  * "&lt;=", "!=").
6930
7111
  * @param value - The value for comparison
6931
- * @returns The created {@link Query}.
7112
+ * @returns The created {@link QueryFieldFilterConstraint}.
6932
7113
  */
6933
7114
  function where(fieldPath, opStr, value) {
6934
7115
  const op = opStr;
6935
7116
  const field = fieldPathFromArgument('where', fieldPath);
6936
- return new QueryFilterConstraint(field, op, value);
7117
+ return QueryFieldFilterConstraint._create(field, op, value);
7118
+ }
7119
+ /**
7120
+ * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
7121
+ * returned by a Firestore query by performing the logical OR or AND of multiple
7122
+ * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
7123
+ * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
7124
+ * {@link and} and can then be passed to {@link query} to create a new query
7125
+ * instance that also contains the `QueryCompositeFilterConstraint`.
7126
+ * @internal TODO remove this internal tag with OR Query support in the server
7127
+ */
7128
+ class QueryCompositeFilterConstraint extends AppliableConstraint {
7129
+ /**
7130
+ * @internal
7131
+ */
7132
+ constructor(
7133
+ /** The type of this query constraint */
7134
+ type, _queryConstraints) {
7135
+ super();
7136
+ this.type = type;
7137
+ this._queryConstraints = _queryConstraints;
7138
+ }
7139
+ static _create(type, _queryConstraints) {
7140
+ return new QueryCompositeFilterConstraint(type, _queryConstraints);
7141
+ }
7142
+ _parse(query) {
7143
+ const parsedFilters = this._queryConstraints
7144
+ .map(queryConstraint => {
7145
+ return queryConstraint._parse(query);
7146
+ })
7147
+ .filter(parsedFilter => parsedFilter.getFilters().length > 0);
7148
+ if (parsedFilters.length === 1) {
7149
+ return parsedFilters[0];
7150
+ }
7151
+ return CompositeFilter.create(parsedFilters, this._getOperator());
7152
+ }
7153
+ _apply(query) {
7154
+ const parsedFilter = this._parse(query);
7155
+ if (parsedFilter.getFilters().length === 0) {
7156
+ // Return the existing query if not adding any more filters (e.g. an empty
7157
+ // composite filter).
7158
+ return query;
7159
+ }
7160
+ validateNewFilter(query._query, parsedFilter);
7161
+ return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, parsedFilter));
7162
+ }
7163
+ _getQueryConstraints() {
7164
+ return this._queryConstraints;
7165
+ }
7166
+ _getOperator() {
7167
+ return this.type === 'and' ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */;
7168
+ }
7169
+ }
7170
+ /**
7171
+ * Creates a {@link QueryCompositeFilterConstraint} that performs a logical OR
7172
+ * of all the provided {@link QueryFilterConstraint}s.
7173
+ *
7174
+ * @param queryConstraints - Optional. The {@link QueryFilterConstraint}s
7175
+ * for OR operation. These must be created with calls to {@link where},
7176
+ * {@link or}, or {@link and}.
7177
+ * @returns The created {@link QueryCompositeFilterConstraint}.
7178
+ * @internal TODO remove this internal tag with OR Query support in the server
7179
+ */
7180
+ function or(...queryConstraints) {
7181
+ // Only support QueryFilterConstraints
7182
+ queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('or', queryConstraint));
7183
+ return QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */, queryConstraints);
7184
+ }
7185
+ /**
7186
+ * Creates a {@link QueryCompositeFilterConstraint} that performs a logical AND
7187
+ * of all the provided {@link QueryFilterConstraint}s.
7188
+ *
7189
+ * @param queryConstraints - Optional. The {@link QueryFilterConstraint}s
7190
+ * for AND operation. These must be created with calls to {@link where},
7191
+ * {@link or}, or {@link and}.
7192
+ * @returns The created {@link QueryCompositeFilterConstraint}.
7193
+ * @internal TODO remove this internal tag with OR Query support in the server
7194
+ */
7195
+ function and(...queryConstraints) {
7196
+ // Only support QueryFilterConstraints
7197
+ queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('and', queryConstraint));
7198
+ return QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */, queryConstraints);
6937
7199
  }
7200
+ /**
7201
+ * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
7202
+ * Firestore query. `QueryOrderByConstraint`s are created by invoking
7203
+ * {@link orderBy} and can then be passed to {@link query} to create a new query
7204
+ * instance that also contains this `QueryOrderByConstraint`.
7205
+ *
7206
+ * Note: Documents that do not contain the orderBy field will not be present in
7207
+ * the query result.
7208
+ */
6938
7209
  class QueryOrderByConstraint extends QueryConstraint {
7210
+ /**
7211
+ * @internal
7212
+ */
6939
7213
  constructor(_field, _direction) {
6940
7214
  super();
6941
7215
  this._field = _field;
6942
7216
  this._direction = _direction;
7217
+ /** The type of this query constraint */
6943
7218
  this.type = 'orderBy';
6944
7219
  }
7220
+ static _create(_field, _direction) {
7221
+ return new QueryOrderByConstraint(_field, _direction);
7222
+ }
6945
7223
  _apply(query) {
6946
7224
  const orderBy = newQueryOrderBy(query._query, this._field, this._direction);
6947
7225
  return new Query(query.firestore, query.converter, queryWithAddedOrderBy(query._query, orderBy));
6948
7226
  }
6949
7227
  }
6950
7228
  /**
6951
- * Creates a {@link QueryConstraint} that sorts the query result by the
7229
+ * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
6952
7230
  * specified field, optionally in descending order instead of ascending.
6953
7231
  *
7232
+ * Note: Documents that do not contain the specified field will not be present
7233
+ * in the query result.
7234
+ *
6954
7235
  * @param fieldPath - The field to sort by.
6955
7236
  * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
6956
7237
  * not specified, order will be ascending.
6957
- * @returns The created {@link Query}.
7238
+ * @returns The created {@link QueryOrderByConstraint}.
6958
7239
  */
6959
7240
  function orderBy(fieldPath, directionStr = 'asc') {
6960
7241
  const direction = directionStr;
6961
7242
  const path = fieldPathFromArgument('orderBy', fieldPath);
6962
- return new QueryOrderByConstraint(path, direction);
7243
+ return QueryOrderByConstraint._create(path, direction);
6963
7244
  }
7245
+ /**
7246
+ * A `QueryLimitConstraint` is used to limit the number of documents returned by
7247
+ * a Firestore query.
7248
+ * `QueryLimitConstraint`s are created by invoking {@link limit} or
7249
+ * {@link limitToLast} and can then be passed to {@link query} to create a new
7250
+ * query instance that also contains this `QueryLimitConstraint`.
7251
+ */
6964
7252
  class QueryLimitConstraint extends QueryConstraint {
6965
- constructor(type, _limit, _limitType) {
7253
+ /**
7254
+ * @internal
7255
+ */
7256
+ constructor(
7257
+ /** The type of this query constraint */
7258
+ type, _limit, _limitType) {
6966
7259
  super();
6967
7260
  this.type = type;
6968
7261
  this._limit = _limit;
6969
7262
  this._limitType = _limitType;
6970
7263
  }
7264
+ static _create(type, _limit, _limitType) {
7265
+ return new QueryLimitConstraint(type, _limit, _limitType);
7266
+ }
6971
7267
  _apply(query) {
6972
7268
  return new Query(query.firestore, query.converter, queryWithLimit(query._query, this._limit, this._limitType));
6973
7269
  }
6974
7270
  }
6975
7271
  /**
6976
- * Creates a {@link QueryConstraint} that only returns the first matching documents.
7272
+ * Creates a {@link QueryLimitConstraint} that only returns the first matching
7273
+ * documents.
6977
7274
  *
6978
7275
  * @param limit - The maximum number of items to return.
6979
- * @returns The created {@link Query}.
7276
+ * @returns The created {@link QueryLimitConstraint}.
6980
7277
  */
6981
7278
  function limit(limit) {
6982
7279
  validatePositiveNumber('limit', limit);
6983
- return new QueryLimitConstraint('limit', limit, "F" /* LimitType.First */);
7280
+ return QueryLimitConstraint._create('limit', limit, "F" /* LimitType.First */);
6984
7281
  }
6985
7282
  /**
6986
- * Creates a {@link QueryConstraint} that only returns the last matching documents.
7283
+ * Creates a {@link QueryLimitConstraint} that only returns the last matching
7284
+ * documents.
6987
7285
  *
6988
7286
  * You must specify at least one `orderBy` clause for `limitToLast` queries,
6989
7287
  * otherwise an exception will be thrown during execution.
6990
7288
  *
6991
7289
  * @param limit - The maximum number of items to return.
6992
- * @returns The created {@link Query}.
7290
+ * @returns The created {@link QueryLimitConstraint}.
6993
7291
  */
6994
7292
  function limitToLast(limit) {
6995
7293
  validatePositiveNumber('limitToLast', limit);
6996
- return new QueryLimitConstraint('limitToLast', limit, "L" /* LimitType.Last */);
7294
+ return QueryLimitConstraint._create('limitToLast', limit, "L" /* LimitType.Last */);
6997
7295
  }
7296
+ /**
7297
+ * A `QueryStartAtConstraint` is used to exclude documents from the start of a
7298
+ * result set returned by a Firestore query.
7299
+ * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
7300
+ * {@link (startAfter:1)} and can then be passed to {@link query} to create a
7301
+ * new query instance that also contains this `QueryStartAtConstraint`.
7302
+ */
6998
7303
  class QueryStartAtConstraint extends QueryConstraint {
6999
- constructor(type, _docOrFields, _inclusive) {
7304
+ /**
7305
+ * @internal
7306
+ */
7307
+ constructor(
7308
+ /** The type of this query constraint */
7309
+ type, _docOrFields, _inclusive) {
7000
7310
  super();
7001
7311
  this.type = type;
7002
7312
  this._docOrFields = _docOrFields;
7003
7313
  this._inclusive = _inclusive;
7004
7314
  }
7315
+ static _create(type, _docOrFields, _inclusive) {
7316
+ return new QueryStartAtConstraint(type, _docOrFields, _inclusive);
7317
+ }
7005
7318
  _apply(query) {
7006
7319
  const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive);
7007
7320
  return new Query(query.firestore, query.converter, queryWithStartAt(query._query, bound));
7008
7321
  }
7009
7322
  }
7010
7323
  function startAt(...docOrFields) {
7011
- return new QueryStartAtConstraint('startAt', docOrFields,
7324
+ return QueryStartAtConstraint._create('startAt', docOrFields,
7012
7325
  /*inclusive=*/ true);
7013
7326
  }
7014
7327
  function startAfter(...docOrFields) {
7015
- return new QueryStartAtConstraint('startAfter', docOrFields,
7328
+ return QueryStartAtConstraint._create('startAfter', docOrFields,
7016
7329
  /*inclusive=*/ false);
7017
7330
  }
7331
+ /**
7332
+ * A `QueryEndAtConstraint` is used to exclude documents from the end of a
7333
+ * result set returned by a Firestore query.
7334
+ * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
7335
+ * {@link (endBefore:1)} and can then be passed to {@link query} to create a new
7336
+ * query instance that also contains this `QueryEndAtConstraint`.
7337
+ */
7018
7338
  class QueryEndAtConstraint extends QueryConstraint {
7019
- constructor(type, _docOrFields, _inclusive) {
7339
+ /**
7340
+ * @internal
7341
+ */
7342
+ constructor(
7343
+ /** The type of this query constraint */
7344
+ type, _docOrFields, _inclusive) {
7020
7345
  super();
7021
7346
  this.type = type;
7022
7347
  this._docOrFields = _docOrFields;
7023
7348
  this._inclusive = _inclusive;
7024
7349
  }
7350
+ static _create(type, _docOrFields, _inclusive) {
7351
+ return new QueryEndAtConstraint(type, _docOrFields, _inclusive);
7352
+ }
7025
7353
  _apply(query) {
7026
7354
  const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive);
7027
7355
  return new Query(query.firestore, query.converter, queryWithEndAt(query._query, bound));
7028
7356
  }
7029
7357
  }
7030
7358
  function endBefore(...docOrFields) {
7031
- return new QueryEndAtConstraint('endBefore', docOrFields,
7359
+ return QueryEndAtConstraint._create('endBefore', docOrFields,
7032
7360
  /*inclusive=*/ false);
7033
7361
  }
7034
7362
  function endAt(...docOrFields) {
7035
- return new QueryEndAtConstraint('endAt', docOrFields, /*inclusive=*/ true);
7363
+ return QueryEndAtConstraint._create('endAt', docOrFields,
7364
+ /*inclusive=*/ true);
7036
7365
  }
7037
7366
  /** Helper function to create a bound from a document or fields */
7038
7367
  function newQueryBoundFromDocOrFields(query, methodName, docOrFields, inclusive) {
@@ -7073,7 +7402,6 @@ function newQueryFilter(query, methodName, dataReader, databaseId, fieldPath, op
7073
7402
  /* allowArrays= */ op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */);
7074
7403
  }
7075
7404
  const filter = FieldFilter.create(fieldPath, op, fieldValue);
7076
- validateNewFilter(query, filter);
7077
7405
  return filter;
7078
7406
  }
7079
7407
  function newQueryOrderBy(query, fieldPath, direction) {
@@ -7272,33 +7600,55 @@ function conflictingOps(op) {
7272
7600
  return [];
7273
7601
  }
7274
7602
  }
7275
- function validateNewFilter(query, filter) {
7276
- if (filter.isInequality()) {
7277
- const existingField = getInequalityFilterField(query);
7278
- if (existingField !== null && !existingField.isEqual(filter.field)) {
7603
+ function validateNewFieldFilter(query, fieldFilter) {
7604
+ if (fieldFilter.isInequality()) {
7605
+ const existingInequality = getInequalityFilterField(query);
7606
+ const newInequality = fieldFilter.field;
7607
+ if (existingInequality !== null &&
7608
+ !existingInequality.isEqual(newInequality)) {
7279
7609
  throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. All where filters with an inequality' +
7280
7610
  ' (<, <=, !=, not-in, >, or >=) must be on the same field. But you have' +
7281
- ` inequality filters on '${existingField.toString()}'` +
7282
- ` and '${filter.field.toString()}'`);
7611
+ ` inequality filters on '${existingInequality.toString()}'` +
7612
+ ` and '${newInequality.toString()}'`);
7283
7613
  }
7284
7614
  const firstOrderByField = getFirstOrderByField(query);
7285
7615
  if (firstOrderByField !== null) {
7286
- validateOrderByAndInequalityMatch(query, filter.field, firstOrderByField);
7616
+ validateOrderByAndInequalityMatch(query, newInequality, firstOrderByField);
7287
7617
  }
7288
7618
  }
7289
- const conflictingOp = findFilterOperator(query, conflictingOps(filter.op));
7619
+ const conflictingOp = findOpInsideFilters(query.filters, conflictingOps(fieldFilter.op));
7290
7620
  if (conflictingOp !== null) {
7291
7621
  // Special case when it's a duplicate op to give a slightly clearer error message.
7292
- if (conflictingOp === filter.op) {
7622
+ if (conflictingOp === fieldFilter.op) {
7293
7623
  throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You cannot use more than one ' +
7294
- `'${filter.op.toString()}' filter.`);
7624
+ `'${fieldFilter.op.toString()}' filter.`);
7295
7625
  }
7296
7626
  else {
7297
- throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You cannot use '${filter.op.toString()}' filters ` +
7627
+ throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +
7298
7628
  `with '${conflictingOp.toString()}' filters.`);
7299
7629
  }
7300
7630
  }
7301
7631
  }
7632
+ function validateNewFilter(query, filter) {
7633
+ let testQuery = query;
7634
+ const subFilters = filter.getFlattenedFilters();
7635
+ for (const subFilter of subFilters) {
7636
+ validateNewFieldFilter(testQuery, subFilter);
7637
+ testQuery = queryWithAddedFilter(testQuery, subFilter);
7638
+ }
7639
+ }
7640
+ // Checks if any of the provided filter operators are included in the given list of filters and
7641
+ // returns the first one that is, or null if none are.
7642
+ function findOpInsideFilters(filters, operators) {
7643
+ for (const filter of filters) {
7644
+ for (const fieldFilter of filter.getFlattenedFilters()) {
7645
+ if (operators.indexOf(fieldFilter.op) >= 0) {
7646
+ return fieldFilter.op;
7647
+ }
7648
+ }
7649
+ }
7650
+ return null;
7651
+ }
7302
7652
  function validateNewOrderBy(query, orderBy) {
7303
7653
  if (getFirstOrderByField(query) === null) {
7304
7654
  // This is the first order by. It must match any inequality.
@@ -7316,6 +7666,24 @@ function validateOrderByAndInequalityMatch(baseQuery, inequality, orderBy) {
7316
7666
  `as your first argument to orderBy(), but your first orderBy() ` +
7317
7667
  `is on field '${orderBy.toString()}' instead.`);
7318
7668
  }
7669
+ }
7670
+ function validateQueryFilterConstraint(functionName, queryConstraint) {
7671
+ if (!(queryConstraint instanceof QueryFieldFilterConstraint) &&
7672
+ !(queryConstraint instanceof QueryCompositeFilterConstraint)) {
7673
+ throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);
7674
+ }
7675
+ }
7676
+ function validateQueryConstraintArray(queryConstraint) {
7677
+ const compositeFilterCount = queryConstraint.filter(filter => filter instanceof QueryCompositeFilterConstraint).length;
7678
+ const fieldFilterCount = queryConstraint.filter(filter => filter instanceof QueryFieldFilterConstraint).length;
7679
+ if (compositeFilterCount > 1 ||
7680
+ (compositeFilterCount > 0 && fieldFilterCount > 0)) {
7681
+ throw new FirestoreError(Code.INVALID_ARGUMENT, 'InvalidQuery. When using composite filters, you cannot use ' +
7682
+ 'more than one filter at the top level. Consider nesting the multiple ' +
7683
+ 'filters within an `and(...)` statement. For example: ' +
7684
+ 'change `query(query, where(...), or(...))` to ' +
7685
+ '`query(query, and(where(...), or(...)))`.');
7686
+ }
7319
7687
  }
7320
7688
 
7321
7689
  /**
@@ -8657,14 +9025,21 @@ exports.Firestore = Firestore;
8657
9025
  exports.FirestoreError = FirestoreError;
8658
9026
  exports.GeoPoint = GeoPoint;
8659
9027
  exports.Query = Query;
9028
+ exports.QueryCompositeFilterConstraint = QueryCompositeFilterConstraint;
8660
9029
  exports.QueryConstraint = QueryConstraint;
8661
9030
  exports.QueryDocumentSnapshot = QueryDocumentSnapshot;
9031
+ exports.QueryEndAtConstraint = QueryEndAtConstraint;
9032
+ exports.QueryFieldFilterConstraint = QueryFieldFilterConstraint;
9033
+ exports.QueryLimitConstraint = QueryLimitConstraint;
9034
+ exports.QueryOrderByConstraint = QueryOrderByConstraint;
8662
9035
  exports.QuerySnapshot = QuerySnapshot;
9036
+ exports.QueryStartAtConstraint = QueryStartAtConstraint;
8663
9037
  exports.Timestamp = Timestamp;
8664
9038
  exports.Transaction = Transaction;
8665
9039
  exports.WriteBatch = WriteBatch;
8666
9040
  exports.addDoc = addDoc;
8667
9041
  exports.aggregateQuerySnapshotEqual = aggregateQuerySnapshotEqual;
9042
+ exports.and = and;
8668
9043
  exports.arrayRemove = arrayRemove;
8669
9044
  exports.arrayUnion = arrayUnion;
8670
9045
  exports.collection = collection;
@@ -8684,6 +9059,7 @@ exports.increment = increment;
8684
9059
  exports.initializeFirestore = initializeFirestore;
8685
9060
  exports.limit = limit;
8686
9061
  exports.limitToLast = limitToLast;
9062
+ exports.or = or;
8687
9063
  exports.orderBy = orderBy;
8688
9064
  exports.query = query;
8689
9065
  exports.queryEqual = queryEqual;