@firebase/firestore 3.4.4-canary.0482aa5b7 → 3.4.4-canary.3e9f3e253

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 (134) hide show
  1. package/dist/firestore/src/api/credentials.d.ts +1 -0
  2. package/dist/firestore/src/local/document_overlay_cache.d.ts +72 -0
  3. package/dist/firestore/src/local/indexeddb_document_overlay_cache.d.ts +45 -0
  4. package/dist/firestore/src/local/indexeddb_index_manager.d.ts +10 -2
  5. package/dist/firestore/src/local/indexeddb_persistence.d.ts +6 -4
  6. package/dist/firestore/src/local/indexeddb_remote_document_cache.d.ts +2 -8
  7. package/dist/firestore/src/local/indexeddb_schema.d.ts +81 -9
  8. package/dist/firestore/src/local/local_documents_view.d.ts +0 -1
  9. package/dist/firestore/src/local/local_serializer.d.ts +18 -2
  10. package/dist/firestore/src/local/memory_document_overlay_cache.d.ts +37 -0
  11. package/dist/firestore/src/local/memory_persistence.d.ts +6 -2
  12. package/dist/firestore/src/local/memory_remote_document_cache.d.ts +1 -3
  13. package/dist/firestore/src/local/persistence.d.ts +8 -2
  14. package/dist/firestore/src/local/remote_document_cache.d.ts +7 -9
  15. package/dist/firestore/src/local/simple_db.d.ts +1 -0
  16. package/dist/firestore/src/model/document_key.d.ts +4 -0
  17. package/dist/firestore/src/model/field_index.d.ts +2 -2
  18. package/dist/firestore/src/model/overlay.d.ts +32 -0
  19. package/dist/firestore/src/model/target_index_matcher.d.ts +70 -0
  20. package/dist/firestore/test/unit/local/counting_query_engine.d.ts +3 -3
  21. package/dist/firestore/test/unit/local/document_overlay_cache.test.d.ts +1 -0
  22. package/dist/firestore/test/unit/local/persistence_test_helpers.d.ts +1 -0
  23. package/dist/firestore/test/unit/local/test_document_overlay_cache.d.ts +38 -0
  24. package/dist/firestore/test/unit/local/test_index_manager.d.ts +11 -0
  25. package/dist/firestore/test/unit/local/test_remote_document_cache.d.ts +4 -2
  26. package/dist/firestore/test/unit/local/test_remote_document_change_buffer.d.ts +1 -1
  27. package/dist/firestore/test/unit/model/target_index_matcher.test.d.ts +17 -0
  28. package/dist/index.esm2017.js +3497 -3134
  29. package/dist/index.esm2017.js.map +1 -1
  30. package/dist/index.esm5.js +3448 -3123
  31. package/dist/index.esm5.js.map +1 -1
  32. package/dist/index.node.cjs.js +639 -154
  33. package/dist/index.node.cjs.js.map +1 -1
  34. package/dist/index.node.mjs +639 -154
  35. package/dist/index.node.mjs.map +1 -1
  36. package/dist/index.rn.js +3586 -3227
  37. package/dist/index.rn.js.map +1 -1
  38. package/dist/internal.d.ts +83 -12
  39. package/dist/lite/firestore/src/api/credentials.d.ts +1 -0
  40. package/dist/lite/firestore/src/local/document_overlay_cache.d.ts +72 -0
  41. package/dist/lite/firestore/src/local/indexeddb_document_overlay_cache.d.ts +45 -0
  42. package/dist/lite/firestore/src/local/indexeddb_index_manager.d.ts +10 -2
  43. package/dist/lite/firestore/src/local/indexeddb_persistence.d.ts +6 -4
  44. package/dist/lite/firestore/src/local/indexeddb_remote_document_cache.d.ts +2 -8
  45. package/dist/lite/firestore/src/local/indexeddb_schema.d.ts +81 -9
  46. package/dist/lite/firestore/src/local/local_documents_view.d.ts +0 -1
  47. package/dist/lite/firestore/src/local/local_serializer.d.ts +18 -2
  48. package/dist/lite/firestore/src/local/memory_document_overlay_cache.d.ts +37 -0
  49. package/dist/lite/firestore/src/local/memory_persistence.d.ts +6 -2
  50. package/dist/lite/firestore/src/local/memory_remote_document_cache.d.ts +1 -3
  51. package/dist/lite/firestore/src/local/persistence.d.ts +8 -2
  52. package/dist/lite/firestore/src/local/remote_document_cache.d.ts +7 -9
  53. package/dist/lite/firestore/src/local/simple_db.d.ts +1 -0
  54. package/dist/lite/firestore/src/model/document_key.d.ts +4 -0
  55. package/dist/lite/firestore/src/model/field_index.d.ts +2 -2
  56. package/dist/lite/firestore/src/model/overlay.d.ts +32 -0
  57. package/dist/lite/firestore/src/model/target_index_matcher.d.ts +70 -0
  58. package/dist/lite/firestore/test/unit/local/counting_query_engine.d.ts +3 -3
  59. package/dist/lite/firestore/test/unit/local/document_overlay_cache.test.d.ts +1 -0
  60. package/dist/lite/firestore/test/unit/local/persistence_test_helpers.d.ts +1 -0
  61. package/dist/lite/firestore/test/unit/local/test_document_overlay_cache.d.ts +38 -0
  62. package/dist/lite/firestore/test/unit/local/test_index_manager.d.ts +11 -0
  63. package/dist/lite/firestore/test/unit/local/test_remote_document_cache.d.ts +4 -2
  64. package/dist/lite/firestore/test/unit/local/test_remote_document_change_buffer.d.ts +1 -1
  65. package/dist/lite/firestore/test/unit/model/target_index_matcher.test.d.ts +17 -0
  66. package/dist/lite/index.browser.esm2017.js +1118 -1112
  67. package/dist/lite/index.browser.esm2017.js.map +1 -1
  68. package/dist/lite/index.browser.esm5.js +53 -47
  69. package/dist/lite/index.browser.esm5.js.map +1 -1
  70. package/dist/lite/index.node.cjs.js +10 -2
  71. package/dist/lite/index.node.cjs.js.map +1 -1
  72. package/dist/lite/index.node.mjs +10 -2
  73. package/dist/lite/index.node.mjs.map +1 -1
  74. package/dist/lite/index.rn.esm2017.js +1134 -1128
  75. package/dist/lite/index.rn.esm2017.js.map +1 -1
  76. package/dist/lite/internal.d.ts +4 -0
  77. package/dist/lite/packages/firestore/dist/lite/index.browser.esm2017.d.ts +112 -112
  78. package/dist/lite/packages/firestore/src/api/credentials.d.ts +1 -0
  79. package/dist/lite/packages/firestore/src/local/document_overlay_cache.d.ts +72 -0
  80. package/dist/lite/packages/firestore/src/local/indexeddb_document_overlay_cache.d.ts +45 -0
  81. package/dist/lite/packages/firestore/src/local/indexeddb_index_manager.d.ts +10 -2
  82. package/dist/lite/packages/firestore/src/local/indexeddb_persistence.d.ts +6 -4
  83. package/dist/lite/packages/firestore/src/local/indexeddb_remote_document_cache.d.ts +2 -8
  84. package/dist/lite/packages/firestore/src/local/indexeddb_schema.d.ts +81 -9
  85. package/dist/lite/packages/firestore/src/local/local_documents_view.d.ts +0 -1
  86. package/dist/lite/packages/firestore/src/local/local_serializer.d.ts +18 -2
  87. package/dist/lite/packages/firestore/src/local/memory_document_overlay_cache.d.ts +37 -0
  88. package/dist/lite/packages/firestore/src/local/memory_persistence.d.ts +6 -2
  89. package/dist/lite/packages/firestore/src/local/memory_remote_document_cache.d.ts +1 -3
  90. package/dist/lite/packages/firestore/src/local/persistence.d.ts +8 -2
  91. package/dist/lite/packages/firestore/src/local/remote_document_cache.d.ts +7 -9
  92. package/dist/lite/packages/firestore/src/local/simple_db.d.ts +1 -0
  93. package/dist/lite/packages/firestore/src/model/document_key.d.ts +4 -0
  94. package/dist/lite/packages/firestore/src/model/field_index.d.ts +2 -2
  95. package/dist/lite/packages/firestore/src/model/overlay.d.ts +32 -0
  96. package/dist/lite/packages/firestore/src/model/target_index_matcher.d.ts +70 -0
  97. package/dist/lite/packages/firestore/test/unit/local/counting_query_engine.d.ts +3 -3
  98. package/dist/lite/packages/firestore/test/unit/local/document_overlay_cache.test.d.ts +1 -0
  99. package/dist/lite/packages/firestore/test/unit/local/persistence_test_helpers.d.ts +1 -0
  100. package/dist/lite/packages/firestore/test/unit/local/test_document_overlay_cache.d.ts +38 -0
  101. package/dist/lite/packages/firestore/test/unit/local/test_index_manager.d.ts +11 -0
  102. package/dist/lite/packages/firestore/test/unit/local/test_remote_document_cache.d.ts +4 -2
  103. package/dist/lite/packages/firestore/test/unit/local/test_remote_document_change_buffer.d.ts +1 -1
  104. package/dist/lite/packages/firestore/test/unit/model/target_index_matcher.test.d.ts +17 -0
  105. package/dist/packages/firestore/dist/index.esm2017.d.ts +181 -179
  106. package/dist/packages/firestore/src/api/credentials.d.ts +1 -0
  107. package/dist/packages/firestore/src/local/document_overlay_cache.d.ts +72 -0
  108. package/dist/packages/firestore/src/local/indexeddb_document_overlay_cache.d.ts +45 -0
  109. package/dist/packages/firestore/src/local/indexeddb_index_manager.d.ts +10 -2
  110. package/dist/packages/firestore/src/local/indexeddb_persistence.d.ts +6 -4
  111. package/dist/packages/firestore/src/local/indexeddb_remote_document_cache.d.ts +2 -8
  112. package/dist/packages/firestore/src/local/indexeddb_schema.d.ts +81 -9
  113. package/dist/packages/firestore/src/local/local_documents_view.d.ts +0 -1
  114. package/dist/packages/firestore/src/local/local_serializer.d.ts +18 -2
  115. package/dist/packages/firestore/src/local/memory_document_overlay_cache.d.ts +37 -0
  116. package/dist/packages/firestore/src/local/memory_persistence.d.ts +6 -2
  117. package/dist/packages/firestore/src/local/memory_remote_document_cache.d.ts +1 -3
  118. package/dist/packages/firestore/src/local/persistence.d.ts +8 -2
  119. package/dist/packages/firestore/src/local/remote_document_cache.d.ts +7 -9
  120. package/dist/packages/firestore/src/local/simple_db.d.ts +1 -0
  121. package/dist/packages/firestore/src/model/document_key.d.ts +4 -0
  122. package/dist/packages/firestore/src/model/field_index.d.ts +2 -2
  123. package/dist/packages/firestore/src/model/overlay.d.ts +32 -0
  124. package/dist/packages/firestore/src/model/target_index_matcher.d.ts +70 -0
  125. package/dist/packages/firestore/test/unit/local/counting_query_engine.d.ts +3 -3
  126. package/dist/packages/firestore/test/unit/local/document_overlay_cache.test.d.ts +1 -0
  127. package/dist/packages/firestore/test/unit/local/persistence_test_helpers.d.ts +1 -0
  128. package/dist/packages/firestore/test/unit/local/test_document_overlay_cache.d.ts +38 -0
  129. package/dist/packages/firestore/test/unit/local/test_index_manager.d.ts +11 -0
  130. package/dist/packages/firestore/test/unit/local/test_remote_document_cache.d.ts +4 -2
  131. package/dist/packages/firestore/test/unit/local/test_remote_document_change_buffer.d.ts +1 -1
  132. package/dist/packages/firestore/test/unit/model/target_index_matcher.test.d.ts +17 -0
  133. package/dist/private.d.ts +79 -12
  134. package/package.json +9 -9
@@ -8,7 +8,7 @@ import { credentials, loadPackageDefinition, Metadata } from '@grpc/grpc-js';
8
8
  import { fromJSON } from '@grpc/proto-loader';
9
9
 
10
10
  const name = "@firebase/firestore";
11
- const version$1 = "3.4.4-canary.0482aa5b7";
11
+ const version$1 = "3.4.4-canary.3e9f3e253";
12
12
 
13
13
  /**
14
14
  * @license
@@ -61,7 +61,7 @@ User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');
61
61
  User.FIRST_PARTY = new User('first-party-uid');
62
62
  User.MOCK_USER = new User('mock-user');
63
63
 
64
- const version = "9.6.5-canary.0482aa5b7";
64
+ const version = "9.6.6-canary.3e9f3e253";
65
65
 
66
66
  /**
67
67
  * @license
@@ -666,13 +666,19 @@ class FirebaseAppCheckTokenProvider {
666
666
  this.appCheckProvider = appCheckProvider;
667
667
  this.forceRefresh = false;
668
668
  this.appCheck = null;
669
+ this.latestAppCheckToken = null;
669
670
  }
670
671
  start(asyncQueue, changeListener) {
671
672
  const onTokenChanged = tokenResult => {
672
673
  if (tokenResult.error != null) {
673
674
  logDebug('FirebaseAppCheckTokenProvider', `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`);
674
675
  }
675
- return changeListener(tokenResult.token);
676
+ const tokenUpdated = tokenResult.token !== this.latestAppCheckToken;
677
+ this.latestAppCheckToken = tokenResult.token;
678
+ logDebug('FirebaseAppCheckTokenProvider', `Received ${tokenUpdated ? 'new' : 'existing'} token.`);
679
+ return tokenUpdated
680
+ ? changeListener(tokenResult.token)
681
+ : Promise.resolve();
676
682
  };
677
683
  this.tokenListener = (tokenResult) => {
678
684
  asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult));
@@ -707,6 +713,7 @@ class FirebaseAppCheckTokenProvider {
707
713
  return this.appCheck.getToken(forceRefresh).then(tokenResult => {
708
714
  if (tokenResult) {
709
715
  hardAssert(typeof tokenResult.token === 'string');
716
+ this.latestAppCheckToken = tokenResult.token;
710
717
  return new AppCheckToken(tokenResult.token);
711
718
  }
712
719
  else {
@@ -1210,9 +1217,10 @@ function decodeResourcePath(path) {
1210
1217
  * an auto-incrementing ID. This is required for Index-Free queries.
1211
1218
  * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.
1212
1219
  * 11. Add bundles and named_queries for bundle support.
1213
- * 12. Add indexing support.
1220
+ * 12. Add document overlays.
1221
+ * 13. Add indexing support.
1214
1222
  */
1215
- const SCHEMA_VERSION = 11;
1223
+ const SCHEMA_VERSION = 12;
1216
1224
  /**
1217
1225
  * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.
1218
1226
  */
@@ -1774,7 +1782,10 @@ DbNamedQuery.keyPath = 'name';
1774
1782
  /** An object representing the global configuration for a field index. */
1775
1783
  class DbIndexConfiguration {
1776
1784
  constructor(
1777
- /** The index id for this entry. */
1785
+ /**
1786
+ * The index id for this entry. Undefined for indexes that are not yet
1787
+ * persisted.
1788
+ */
1778
1789
  indexId,
1779
1790
  /** The collection group this index belongs to. */
1780
1791
  collectionGroup,
@@ -1788,6 +1799,16 @@ class DbIndexConfiguration {
1788
1799
  /** Name of the IndexedDb object store. */
1789
1800
  DbIndexConfiguration.store = 'indexConfiguration';
1790
1801
  DbIndexConfiguration.keyPath = 'indexId';
1802
+ /**
1803
+ * An index that provides access to the index configurations by collection
1804
+ * group.
1805
+ *
1806
+ * PORTING NOTE: iOS and Android maintain this index in-memory, but this is
1807
+ * not possible here as the Web client supports concurrent access to
1808
+ * persistence via multi-tab.
1809
+ */
1810
+ DbIndexConfiguration.collectionGroupIndex = 'collectionGroupIndex';
1811
+ DbIndexConfiguration.collectionGroupIndexPath = 'collectionGroup';
1791
1812
  /**
1792
1813
  * An object describing how up-to-date the index backfill is for each user and
1793
1814
  * index.
@@ -1829,8 +1850,18 @@ class DbIndexState {
1829
1850
  /** Name of the IndexedDb object store. */
1830
1851
  DbIndexState.store = 'indexState';
1831
1852
  DbIndexState.keyPath = ['indexId', 'uid'];
1853
+ /**
1854
+ * An index that provides access to documents in a collection sorted by last
1855
+ * update time. Used by the backfiller.
1856
+ *
1857
+ * PORTING NOTE: iOS and Android maintain this index in-memory, but this is
1858
+ * not possible here as the Web client supports concurrent access to
1859
+ * persistence via multi-tab.
1860
+ */
1861
+ DbIndexState.sequenceNumberIndex = 'sequenceNumberIndex';
1862
+ DbIndexState.sequenceNumberIndexPath = ['uid', 'sequenceNumber'];
1832
1863
  /** An object that stores the encoded entries for all documents and fields. */
1833
- class DbIndexEntries {
1864
+ class DbIndexEntry {
1834
1865
  constructor(
1835
1866
  /** The index id for this entry. */
1836
1867
  indexId,
@@ -1850,14 +1881,54 @@ class DbIndexEntries {
1850
1881
  }
1851
1882
  }
1852
1883
  /** Name of the IndexedDb object store. */
1853
- DbIndexEntries.store = 'indexEntries';
1854
- DbIndexEntries.keyPath = [
1884
+ DbIndexEntry.store = 'indexEntries';
1885
+ DbIndexEntry.keyPath = [
1855
1886
  'indexId',
1856
1887
  'uid',
1857
1888
  'arrayValue',
1858
1889
  'directionalValue',
1859
1890
  'documentKey'
1860
1891
  ];
1892
+ /**
1893
+ * An object representing a document overlay.
1894
+ */
1895
+ class DbDocumentOverlay {
1896
+ constructor(
1897
+ /** The user ID to whom this overlay belongs. */
1898
+ userId,
1899
+ /** The path to the collection that contains the document. */
1900
+ collectionPath,
1901
+ /** The ID (key) of the document within the collection. */
1902
+ documentId,
1903
+ /** The collection group to which the document belongs. */
1904
+ collectionGroup,
1905
+ /** The largest batch ID that's been applied for this overlay. */
1906
+ largestBatchId,
1907
+ /** The overlay mutation. */
1908
+ overlayMutation) {
1909
+ this.userId = userId;
1910
+ this.collectionPath = collectionPath;
1911
+ this.documentId = documentId;
1912
+ this.collectionGroup = collectionGroup;
1913
+ this.largestBatchId = largestBatchId;
1914
+ this.overlayMutation = overlayMutation;
1915
+ }
1916
+ }
1917
+ /** Name of the IndexedDb object store. */
1918
+ DbDocumentOverlay.store = 'documentOverlays';
1919
+ DbDocumentOverlay.keyPath = ['userId', 'collectionPath', 'documentId'];
1920
+ DbDocumentOverlay.collectionPathOverlayIndex = 'collectionPathOverlayIndex';
1921
+ DbDocumentOverlay.collectionPathOverlayIndexPath = [
1922
+ 'userId',
1923
+ 'collectionPath',
1924
+ 'largestBatchId'
1925
+ ];
1926
+ DbDocumentOverlay.collectionGroupOverlayIndex = 'collectionGroupOverlayIndex';
1927
+ DbDocumentOverlay.collectionGroupOverlayIndexPath = [
1928
+ 'userId',
1929
+ 'collectionGroup',
1930
+ 'largestBatchId'
1931
+ ];
1861
1932
  // Visible for testing
1862
1933
  const V1_STORES = [
1863
1934
  DbMutationQueue.store,
@@ -1881,18 +1952,28 @@ const V8_STORES = [...V6_STORES, DbCollectionParent.store];
1881
1952
  // V9 does not change the set of stores.
1882
1953
  // V10 does not change the set of stores.
1883
1954
  const V11_STORES = [...V8_STORES, DbBundle.store, DbNamedQuery.store];
1884
- [
1885
- ...V11_STORES,
1955
+ const V12_STORES = [...V11_STORES, DbDocumentOverlay.store];
1956
+ const V13_STORES = [
1957
+ ...V12_STORES,
1886
1958
  DbIndexConfiguration.store,
1887
1959
  DbIndexState.store,
1888
- DbIndexEntries.store
1960
+ DbIndexEntry.store
1889
1961
  ];
1890
- /**
1891
- * The list of all default IndexedDB stores used throughout the SDK. This is
1892
- * used when creating transactions so that access across all stores is done
1893
- * atomically.
1894
- */
1895
- const ALL_STORES = V11_STORES;
1962
+ /** Returns the object stores for the provided schema. */
1963
+ function getObjectStores(schemaVersion) {
1964
+ if (schemaVersion === 13) {
1965
+ return V13_STORES;
1966
+ }
1967
+ else if (schemaVersion === 12) {
1968
+ return V12_STORES;
1969
+ }
1970
+ else if (schemaVersion === 11) {
1971
+ return V11_STORES;
1972
+ }
1973
+ else {
1974
+ fail();
1975
+ }
1976
+ }
1896
1977
 
1897
1978
  /**
1898
1979
  * @license
@@ -2189,6 +2270,15 @@ class SimpleDbTransaction {
2189
2270
  this.transaction.abort();
2190
2271
  }
2191
2272
  }
2273
+ maybeCommit() {
2274
+ // If the browser supports V3 IndexedDB, we invoke commit() explicitly to
2275
+ // speed up index DB processing if the event loop remains blocks.
2276
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2277
+ const maybeV3IndexedDb = this.transaction;
2278
+ if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') {
2279
+ maybeV3IndexedDb.commit();
2280
+ }
2281
+ }
2192
2282
  /**
2193
2283
  * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All
2194
2284
  * operations performed on the SimpleDbStore happen within the context of this
@@ -2385,6 +2475,10 @@ class SimpleDb {
2385
2475
  this.db = await this.ensureDb(action);
2386
2476
  const transaction = SimpleDbTransaction.open(this.db, action, readonly ? 'readonly' : 'readwrite', objectStores);
2387
2477
  const transactionFnResult = transactionFn(transaction)
2478
+ .next(result => {
2479
+ transaction.maybeCommit();
2480
+ return result;
2481
+ })
2388
2482
  .catch(error => {
2389
2483
  // Abort the transaction if there was an error.
2390
2484
  transaction.abort(error);
@@ -2557,13 +2651,29 @@ class SimpleDbStore {
2557
2651
  return wrapRequest(request);
2558
2652
  }
2559
2653
  loadAll(indexOrRange, range) {
2560
- const cursor = this.cursor(this.options(indexOrRange, range));
2561
- const results = [];
2562
- return this.iterateCursor(cursor, (key, value) => {
2563
- results.push(value);
2564
- }).next(() => {
2565
- return results;
2566
- });
2654
+ const iterateOptions = this.options(indexOrRange, range);
2655
+ // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly
2656
+ // 20% faster. Unfortunately, getAll() does not support custom indices.
2657
+ if (!iterateOptions.index && typeof this.store.getAll === 'function') {
2658
+ const request = this.store.getAll(iterateOptions.range);
2659
+ return new PersistencePromise((resolve, reject) => {
2660
+ request.onerror = (event) => {
2661
+ reject(event.target.error);
2662
+ };
2663
+ request.onsuccess = (event) => {
2664
+ resolve(event.target.result);
2665
+ };
2666
+ });
2667
+ }
2668
+ else {
2669
+ const cursor = this.cursor(iterateOptions);
2670
+ const results = [];
2671
+ return this.iterateCursor(cursor, (key, value) => {
2672
+ results.push(value);
2673
+ }).next(() => {
2674
+ return results;
2675
+ });
2676
+ }
2567
2677
  }
2568
2678
  deleteAll(indexOrRange, range) {
2569
2679
  logDebug(LOG_TAG$g, 'DELETE ALL', this.store.name);
@@ -3594,6 +3704,14 @@ class DocumentKey {
3594
3704
  return (this.path.length >= 2 &&
3595
3705
  this.path.get(this.path.length - 2) === collectionId);
3596
3706
  }
3707
+ /** Returns the collection group (i.e. the name of the parent collection) for this key. */
3708
+ getCollectionGroup() {
3709
+ return this.path.get(this.path.length - 2);
3710
+ }
3711
+ /** Returns the fully qualified path to the parent collection. */
3712
+ getCollectionPath() {
3713
+ return this.path.popLast();
3714
+ }
3597
3715
  isEqual(other) {
3598
3716
  return (other !== null && ResourcePath.comparator(this.path, other.path) === 0);
3599
3717
  }
@@ -4417,12 +4535,12 @@ class FieldIndex {
4417
4535
  /** The collection ID this index applies to. */
4418
4536
  collectionGroup,
4419
4537
  /** The field segments for this index. */
4420
- segments,
4538
+ fields,
4421
4539
  /** Shows how up-to-date the index is for the current user. */
4422
4540
  indexState) {
4423
4541
  this.indexId = indexId;
4424
4542
  this.collectionGroup = collectionGroup;
4425
- this.segments = segments;
4543
+ this.fields = fields;
4426
4544
  this.indexState = indexState;
4427
4545
  }
4428
4546
  }
@@ -6682,6 +6800,47 @@ class MutationBatchResult {
6682
6800
  }
6683
6801
  }
6684
6802
 
6803
+ /**
6804
+ * @license
6805
+ * Copyright 2022 Google LLC
6806
+ *
6807
+ * Licensed under the Apache License, Version 2.0 (the "License");
6808
+ * you may not use this file except in compliance with the License.
6809
+ * You may obtain a copy of the License at
6810
+ *
6811
+ * http://www.apache.org/licenses/LICENSE-2.0
6812
+ *
6813
+ * Unless required by applicable law or agreed to in writing, software
6814
+ * distributed under the License is distributed on an "AS IS" BASIS,
6815
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6816
+ * See the License for the specific language governing permissions and
6817
+ * limitations under the License.
6818
+ */
6819
+ /**
6820
+ * Representation of an overlay computed by Firestore.
6821
+ *
6822
+ * Holds information about a mutation and the largest batch id in Firestore when
6823
+ * the mutation was created.
6824
+ */
6825
+ class Overlay {
6826
+ constructor(largestBatchId, mutation) {
6827
+ this.largestBatchId = largestBatchId;
6828
+ this.mutation = mutation;
6829
+ }
6830
+ getKey() {
6831
+ return this.mutation.key;
6832
+ }
6833
+ isEqual(other) {
6834
+ return other !== null && this.mutation === other.mutation;
6835
+ }
6836
+ toString() {
6837
+ return `Overlay{
6838
+ largestBatchId: ${this.largestBatchId},
6839
+ mutation: ${this.mutation.toString()}
6840
+ }`;
6841
+ }
6842
+ }
6843
+
6685
6844
  /**
6686
6845
  * @license
6687
6846
  * Copyright 2017 Google LLC
@@ -8683,6 +8842,37 @@ function fromBundleMetadata(metadata) {
8683
8842
  version: metadata.version,
8684
8843
  createTime: fromVersion(metadata.createTime)
8685
8844
  };
8845
+ }
8846
+ /** Encodes a DbDocumentOverlay object to an Overlay model object. */
8847
+ function fromDbDocumentOverlay(localSerializer, dbDocumentOverlay) {
8848
+ return new Overlay(dbDocumentOverlay.largestBatchId, fromMutation(localSerializer.remoteSerializer, dbDocumentOverlay.overlayMutation));
8849
+ }
8850
+ /** Decodes an Overlay model object into a DbDocumentOverlay object. */
8851
+ function toDbDocumentOverlay(localSerializer, userId, overlay) {
8852
+ const [_, collectionPath, documentId] = toDbDocumentOverlayKey(userId, overlay.mutation.key);
8853
+ return new DbDocumentOverlay(userId, collectionPath, documentId, overlay.mutation.key.getCollectionGroup(), overlay.largestBatchId, toMutation(localSerializer.remoteSerializer, overlay.mutation));
8854
+ }
8855
+ /**
8856
+ * Returns the DbDocumentOverlayKey corresponding to the given user and
8857
+ * document key.
8858
+ */
8859
+ function toDbDocumentOverlayKey(userId, docKey) {
8860
+ const docId = docKey.path.lastSegment();
8861
+ const collectionPath = encodeResourcePath(docKey.path.popLast());
8862
+ return [userId, collectionPath, docId];
8863
+ }
8864
+ function toDbIndexConfiguration(index) {
8865
+ return new DbIndexConfiguration(index.indexId, index.collectionGroup, index.fields.map(s => [s.fieldPath.canonicalString(), s.kind]));
8866
+ }
8867
+ function fromDbIndexConfiguration(index, state) {
8868
+ const decodedState = state
8869
+ ? new IndexState(state.sequenceNumber, new IndexOffset(fromDbTimestamp(state.readTime), new DocumentKey(decodeResourcePath(state.documentKey)), state.largestBatchId))
8870
+ : IndexState.empty();
8871
+ const decodedSegments = index.fields.map(([fieldPath, kind]) => new IndexSegment(FieldPath$1.fromServerFormat(fieldPath), kind));
8872
+ return new FieldIndex(index.indexId, index.collectionGroup, decodedSegments, decodedState);
8873
+ }
8874
+ function toDbIndexState(indexId, user, sequenceNumber, offset) {
8875
+ return new DbIndexState(indexId, user.uid || '', sequenceNumber, toDbTimestamp(offset.readTime), encodeResourcePath(offset.documentKey.path), offset.largestBatchId);
8686
8876
  }
8687
8877
 
8688
8878
  /**
@@ -8742,6 +8932,125 @@ function namedQueriesStore(txn) {
8742
8932
  return getStore(txn, DbNamedQuery.store);
8743
8933
  }
8744
8934
 
8935
+ /**
8936
+ * @license
8937
+ * Copyright 2022 Google LLC
8938
+ *
8939
+ * Licensed under the Apache License, Version 2.0 (the "License");
8940
+ * you may not use this file except in compliance with the License.
8941
+ * You may obtain a copy of the License at
8942
+ *
8943
+ * http://www.apache.org/licenses/LICENSE-2.0
8944
+ *
8945
+ * Unless required by applicable law or agreed to in writing, software
8946
+ * distributed under the License is distributed on an "AS IS" BASIS,
8947
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8948
+ * See the License for the specific language governing permissions and
8949
+ * limitations under the License.
8950
+ */
8951
+ /**
8952
+ * Implementation of DocumentOverlayCache using IndexedDb.
8953
+ */
8954
+ class IndexedDbDocumentOverlayCache {
8955
+ /**
8956
+ * @param serializer - The document serializer.
8957
+ * @param userId - The userId for which we are accessing overlays.
8958
+ */
8959
+ constructor(serializer, userId) {
8960
+ this.serializer = serializer;
8961
+ this.userId = userId;
8962
+ }
8963
+ static forUser(serializer, user) {
8964
+ const userId = user.uid || '';
8965
+ return new IndexedDbDocumentOverlayCache(serializer, userId);
8966
+ }
8967
+ getOverlay(transaction, key) {
8968
+ return documentOverlayStore(transaction)
8969
+ .get(toDbDocumentOverlayKey(this.userId, key))
8970
+ .next(dbOverlay => {
8971
+ if (dbOverlay) {
8972
+ return fromDbDocumentOverlay(this.serializer, dbOverlay);
8973
+ }
8974
+ return null;
8975
+ });
8976
+ }
8977
+ saveOverlays(transaction, largestBatchId, overlays) {
8978
+ const promises = [];
8979
+ overlays.forEach(mutation => {
8980
+ const overlay = new Overlay(largestBatchId, mutation);
8981
+ promises.push(this.saveOverlay(transaction, overlay));
8982
+ });
8983
+ return PersistencePromise.waitFor(promises);
8984
+ }
8985
+ removeOverlaysForBatchId(transaction, documentKeys, batchId) {
8986
+ const collectionPaths = new Set();
8987
+ // Get the set of unique collection paths.
8988
+ documentKeys.forEach(key => collectionPaths.add(encodeResourcePath(key.getCollectionPath())));
8989
+ const promises = [];
8990
+ collectionPaths.forEach(collectionPath => {
8991
+ const range = IDBKeyRange.bound([this.userId, collectionPath, batchId], [this.userId, collectionPath, batchId + 1],
8992
+ /*lowerOpen=*/ false,
8993
+ /*upperOpen=*/ true);
8994
+ promises.push(documentOverlayStore(transaction).deleteAll(DbDocumentOverlay.collectionPathOverlayIndex, range));
8995
+ });
8996
+ return PersistencePromise.waitFor(promises);
8997
+ }
8998
+ getOverlaysForCollection(transaction, collection, sinceBatchId) {
8999
+ const result = new Map();
9000
+ const collectionPath = encodeResourcePath(collection);
9001
+ // We want batch IDs larger than `sinceBatchId`, and so the lower bound
9002
+ // is not inclusive.
9003
+ const range = IDBKeyRange.bound([this.userId, collectionPath, sinceBatchId], [this.userId, collectionPath, Number.POSITIVE_INFINITY],
9004
+ /*lowerOpen=*/ true);
9005
+ return documentOverlayStore(transaction)
9006
+ .loadAll(DbDocumentOverlay.collectionPathOverlayIndex, range)
9007
+ .next(dbOverlays => {
9008
+ for (const dbOverlay of dbOverlays) {
9009
+ const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);
9010
+ result.set(overlay.getKey(), overlay);
9011
+ }
9012
+ return result;
9013
+ });
9014
+ }
9015
+ getOverlaysForCollectionGroup(transaction, collectionGroup, sinceBatchId, count) {
9016
+ const result = new Map();
9017
+ let currentBatchId = undefined;
9018
+ // We want batch IDs larger than `sinceBatchId`, and so the lower bound
9019
+ // is not inclusive.
9020
+ const range = IDBKeyRange.bound([this.userId, collectionGroup, sinceBatchId], [this.userId, collectionGroup, Number.POSITIVE_INFINITY],
9021
+ /*lowerOpen=*/ true);
9022
+ return documentOverlayStore(transaction)
9023
+ .iterate({
9024
+ index: DbDocumentOverlay.collectionGroupOverlayIndex,
9025
+ range
9026
+ }, (_, dbOverlay, control) => {
9027
+ // We do not want to return partial batch overlays, even if the size
9028
+ // of the result set exceeds the given `count` argument. Therefore, we
9029
+ // continue to aggregate results even after the result size exceeds
9030
+ // `count` if there are more overlays from the `currentBatchId`.
9031
+ const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);
9032
+ if (result.size < count ||
9033
+ overlay.largestBatchId === currentBatchId) {
9034
+ result.set(overlay.getKey(), overlay);
9035
+ currentBatchId = overlay.largestBatchId;
9036
+ }
9037
+ else {
9038
+ control.done();
9039
+ }
9040
+ })
9041
+ .next(() => result);
9042
+ }
9043
+ saveOverlay(transaction, overlay) {
9044
+ return documentOverlayStore(transaction).put(toDbDocumentOverlay(this.serializer, this.userId, overlay));
9045
+ }
9046
+ }
9047
+ /**
9048
+ * Helper to get a typed SimpleDbStore for the document overlay object store.
9049
+ */
9050
+ function documentOverlayStore(txn) {
9051
+ return getStore(txn, DbDocumentOverlay.store);
9052
+ }
9053
+
8745
9054
  /**
8746
9055
  * @license
8747
9056
  * Copyright 2019 Google LLC
@@ -8855,17 +9164,22 @@ class MemoryCollectionParentIndex {
8855
9164
  */
8856
9165
  /**
8857
9166
  * A persisted implementation of IndexManager.
9167
+ *
9168
+ * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index
9169
+ * data as it supports multi-tab access.
8858
9170
  */
8859
9171
  class IndexedDbIndexManager {
8860
- constructor() {
9172
+ constructor(user) {
9173
+ this.user = user;
8861
9174
  /**
8862
9175
  * An in-memory copy of the index entries we've already written since the SDK
8863
9176
  * launched. Used to avoid re-writing the same entry repeatedly.
8864
9177
  *
8865
- * This is *NOT* a complete cache of what's in persistence and so can never be used to
8866
- * satisfy reads.
9178
+ * This is *NOT* a complete cache of what's in persistence and so can never be
9179
+ * used to satisfy reads.
8867
9180
  */
8868
9181
  this.collectionParentsCache = new MemoryCollectionParentIndex();
9182
+ this.uid = user.uid || '';
8869
9183
  }
8870
9184
  /**
8871
9185
  * Adds a new entry to the collection parent index.
@@ -8913,12 +9227,25 @@ class IndexedDbIndexManager {
8913
9227
  });
8914
9228
  }
8915
9229
  addFieldIndex(transaction, index) {
8916
- // TODO(indexing): Implement
8917
- return PersistencePromise.resolve();
9230
+ // TODO(indexing): Verify that the auto-incrementing index ID works in
9231
+ // Safari & Firefox.
9232
+ const indexes = indexConfigurationStore(transaction);
9233
+ const dbIndex = toDbIndexConfiguration(index);
9234
+ delete dbIndex.indexId; // `indexId` is auto-populated by IndexedDb
9235
+ return indexes.add(dbIndex).next();
8918
9236
  }
8919
9237
  deleteFieldIndex(transaction, index) {
8920
- // TODO(indexing): Implement
8921
- return PersistencePromise.resolve();
9238
+ const indexes = indexConfigurationStore(transaction);
9239
+ const states = indexStateStore(transaction);
9240
+ const entries = indexEntriesStore(transaction);
9241
+ return indexes
9242
+ .delete(index.indexId)
9243
+ .next(() => states.delete(IDBKeyRange.bound([index.indexId], [index.indexId + 1],
9244
+ /*lowerOpen=*/ false,
9245
+ /*upperOpen=*/ true)))
9246
+ .next(() => entries.delete(IDBKeyRange.bound([index.indexId], [index.indexId + 1],
9247
+ /*lowerOpen=*/ false,
9248
+ /*upperOpen=*/ true)));
8922
9249
  }
8923
9250
  getDocumentsMatchingTarget(transaction, fieldIndex, target) {
8924
9251
  // TODO(indexing): Implement
@@ -8929,21 +9256,55 @@ class IndexedDbIndexManager {
8929
9256
  return PersistencePromise.resolve(null);
8930
9257
  }
8931
9258
  getFieldIndexes(transaction, collectionGroup) {
8932
- // TODO(indexing): Implement
8933
- return PersistencePromise.resolve([]);
9259
+ const indexes = indexConfigurationStore(transaction);
9260
+ const states = indexStateStore(transaction);
9261
+ return (collectionGroup
9262
+ ? indexes.loadAll(DbIndexConfiguration.collectionGroupIndex, IDBKeyRange.bound(collectionGroup, collectionGroup))
9263
+ : indexes.loadAll()).next(indexConfigs => {
9264
+ const result = [];
9265
+ return PersistencePromise.forEach(indexConfigs, (indexConfig) => {
9266
+ return states
9267
+ .get([indexConfig.indexId, this.uid])
9268
+ .next(indexState => {
9269
+ result.push(fromDbIndexConfiguration(indexConfig, indexState));
9270
+ });
9271
+ }).next(() => result);
9272
+ });
8934
9273
  }
8935
9274
  getNextCollectionGroupToUpdate(transaction) {
8936
- // TODO(indexing): Implement
8937
- return PersistencePromise.resolve(null);
9275
+ return this.getFieldIndexes(transaction).next(indexes => {
9276
+ if (indexes.length === 0) {
9277
+ return null;
9278
+ }
9279
+ indexes.sort((l, r) => l.indexState.sequenceNumber - r.indexState.sequenceNumber);
9280
+ return indexes[0].collectionGroup;
9281
+ });
8938
9282
  }
8939
9283
  updateCollectionGroup(transaction, collectionGroup, offset) {
8940
- // TODO(indexing): Implement
8941
- return PersistencePromise.resolve();
9284
+ const indexes = indexConfigurationStore(transaction);
9285
+ const states = indexStateStore(transaction);
9286
+ return this.getNextSequenceNumber(transaction).next(nextSequenceNumber => indexes
9287
+ .loadAll(DbIndexConfiguration.collectionGroupIndex, IDBKeyRange.bound(collectionGroup, collectionGroup))
9288
+ .next(configs => PersistencePromise.forEach(configs, (config) => states.put(toDbIndexState(config.indexId, this.user, nextSequenceNumber, offset)))));
8942
9289
  }
8943
9290
  updateIndexEntries(transaction, documents) {
8944
9291
  // TODO(indexing): Implement
8945
9292
  return PersistencePromise.resolve();
8946
9293
  }
9294
+ getNextSequenceNumber(transaction) {
9295
+ let nextSequenceNumber = 1;
9296
+ const states = indexStateStore(transaction);
9297
+ return states
9298
+ .iterate({
9299
+ index: DbIndexState.sequenceNumberIndex,
9300
+ reverse: true,
9301
+ range: IDBKeyRange.upperBound([this.uid, Number.MAX_SAFE_INTEGER])
9302
+ }, (_, state, controller) => {
9303
+ controller.done();
9304
+ nextSequenceNumber = state.sequenceNumber + 1;
9305
+ })
9306
+ .next(() => nextSequenceNumber);
9307
+ }
8947
9308
  }
8948
9309
  /**
8949
9310
  * Helper to get a typed SimpleDbStore for the collectionParents
@@ -8951,6 +9312,24 @@ class IndexedDbIndexManager {
8951
9312
  */
8952
9313
  function collectionParentsStore(txn) {
8953
9314
  return getStore(txn, DbCollectionParent.store);
9315
+ }
9316
+ /**
9317
+ * Helper to get a typed SimpleDbStore for the index entry object store.
9318
+ */
9319
+ function indexEntriesStore(txn) {
9320
+ return getStore(txn, DbIndexEntry.store);
9321
+ }
9322
+ /**
9323
+ * Helper to get a typed SimpleDbStore for the index configuration object store.
9324
+ */
9325
+ function indexConfigurationStore(txn) {
9326
+ return getStore(txn, DbIndexConfiguration.store);
9327
+ }
9328
+ /**
9329
+ * Helper to get a typed SimpleDbStore for the index state object store.
9330
+ */
9331
+ function indexStateStore(txn) {
9332
+ return getStore(txn, DbIndexState.store);
8954
9333
  }
8955
9334
 
8956
9335
  /**
@@ -10420,12 +10799,10 @@ class RemoteDocumentChangeBuffer {
10420
10799
  * `newIndexedDbRemoteDocumentCache()`.
10421
10800
  */
10422
10801
  class IndexedDbRemoteDocumentCacheImpl {
10423
- /**
10424
- * @param serializer - The document serializer.
10425
- * @param indexManager - The query indexes that need to be maintained.
10426
- */
10427
- constructor(serializer, indexManager) {
10802
+ constructor(serializer) {
10428
10803
  this.serializer = serializer;
10804
+ }
10805
+ setIndexManager(indexManager) {
10429
10806
  this.indexManager = indexManager;
10430
10807
  }
10431
10808
  /**
@@ -10547,21 +10924,21 @@ class IndexedDbRemoteDocumentCacheImpl {
10547
10924
  }
10548
10925
  });
10549
10926
  }
10550
- getDocumentsMatchingQuery(transaction, query, sinceReadTime) {
10927
+ getAll(transaction, collection, sinceReadTime) {
10551
10928
  let results = mutableDocumentMap();
10552
- const immediateChildrenPathLength = query.path.length + 1;
10929
+ const immediateChildrenPathLength = collection.length + 1;
10553
10930
  const iterationOptions = {};
10554
10931
  if (sinceReadTime.isEqual(SnapshotVersion.min())) {
10555
10932
  // Documents are ordered by key, so we can use a prefix scan to narrow
10556
10933
  // down the documents we need to match the query against.
10557
- const startKey = query.path.toArray();
10934
+ const startKey = collection.toArray();
10558
10935
  iterationOptions.range = IDBKeyRange.lowerBound(startKey);
10559
10936
  }
10560
10937
  else {
10561
10938
  // Execute an index-free query and filter by read time. This is safe
10562
10939
  // since all document changes to queries that have a
10563
10940
  // lastLimboFreeSnapshotVersion (`sinceReadTime`) have a read time set.
10564
- const collectionKey = query.path.toArray();
10941
+ const collectionKey = collection.toArray();
10565
10942
  const readTimeKey = toDbTimestampKey(sinceReadTime);
10566
10943
  iterationOptions.range = IDBKeyRange.lowerBound([collectionKey, readTimeKey],
10567
10944
  /* open= */ true);
@@ -10578,12 +10955,12 @@ class IndexedDbRemoteDocumentCacheImpl {
10578
10955
  return;
10579
10956
  }
10580
10957
  const document = this.maybeDecodeDocument(DocumentKey.fromSegments(key), dbRemoteDoc);
10581
- if (!query.path.isPrefixOf(document.key.path)) {
10582
- control.done();
10583
- }
10584
- else if (queryMatches(query, document)) {
10958
+ if (collection.isPrefixOf(document.key.path)) {
10585
10959
  results = results.insert(document.key, document);
10586
10960
  }
10961
+ else {
10962
+ control.done();
10963
+ }
10587
10964
  })
10588
10965
  .next(() => results);
10589
10966
  }
@@ -10621,14 +10998,9 @@ class IndexedDbRemoteDocumentCacheImpl {
10621
10998
  return MutableDocument.newInvalidDocument(documentKey);
10622
10999
  }
10623
11000
  }
10624
- /**
10625
- * Creates a new IndexedDbRemoteDocumentCache.
10626
- *
10627
- * @param serializer - The document serializer.
10628
- * @param indexManager - The query indexes that need to be maintained.
10629
- */
10630
- function newIndexedDbRemoteDocumentCache(serializer, indexManager) {
10631
- return new IndexedDbRemoteDocumentCacheImpl(serializer, indexManager);
11001
+ /** Creates a new IndexedDbRemoteDocumentCache. */
11002
+ function newIndexedDbRemoteDocumentCache(serializer) {
11003
+ return new IndexedDbRemoteDocumentCacheImpl(serializer);
10632
11004
  }
10633
11005
  /**
10634
11006
  * Returns the set of documents that have changed since the specified read
@@ -10862,6 +11234,11 @@ class SchemaConverter {
10862
11234
  });
10863
11235
  }
10864
11236
  if (fromVersion < 12 && toVersion >= 12) {
11237
+ p = p.next(() => {
11238
+ createDocumentOverlayStore(db);
11239
+ });
11240
+ }
11241
+ if (fromVersion < 13 && toVersion >= 13) {
10865
11242
  p = p.next(() => {
10866
11243
  createFieldIndex(db);
10867
11244
  });
@@ -11074,15 +11451,25 @@ function createNamedQueriesStore(db) {
11074
11451
  });
11075
11452
  }
11076
11453
  function createFieldIndex(db) {
11077
- db.createObjectStore(DbIndexConfiguration.store, {
11078
- keyPath: DbIndexConfiguration.keyPath
11454
+ const indexConfiguratioStore = db.createObjectStore(DbIndexConfiguration.store, {
11455
+ keyPath: DbIndexConfiguration.keyPath,
11456
+ autoIncrement: true
11079
11457
  });
11080
- db.createObjectStore(DbIndexState.store, {
11458
+ indexConfiguratioStore.createIndex(DbIndexConfiguration.collectionGroupIndex, DbIndexConfiguration.collectionGroupIndexPath, { unique: false });
11459
+ const indexStateStore = db.createObjectStore(DbIndexState.store, {
11081
11460
  keyPath: DbIndexState.keyPath
11082
11461
  });
11083
- db.createObjectStore(DbIndexEntries.store, {
11084
- keyPath: DbIndexEntries.keyPath
11462
+ indexStateStore.createIndex(DbIndexState.sequenceNumberIndex, DbIndexState.sequenceNumberIndexPath, { unique: false });
11463
+ db.createObjectStore(DbIndexEntry.store, {
11464
+ keyPath: DbIndexEntry.keyPath
11465
+ });
11466
+ }
11467
+ function createDocumentOverlayStore(db) {
11468
+ const documentOverlayStore = db.createObjectStore(DbDocumentOverlay.store, {
11469
+ keyPath: DbDocumentOverlay.keyPath
11085
11470
  });
11471
+ documentOverlayStore.createIndex(DbDocumentOverlay.collectionPathOverlayIndex, DbDocumentOverlay.collectionPathOverlayIndexPath, { unique: false });
11472
+ documentOverlayStore.createIndex(DbDocumentOverlay.collectionGroupOverlayIndex, DbDocumentOverlay.collectionGroupOverlayIndexPath, { unique: false });
11086
11473
  }
11087
11474
 
11088
11475
  /**
@@ -11194,7 +11581,7 @@ class IndexedDbPersistence {
11194
11581
  * If set to true, forcefully obtains database access. Existing tabs will
11195
11582
  * no longer be able to access IndexedDB.
11196
11583
  */
11197
- forceOwningTab) {
11584
+ forceOwningTab, schemaVersion = SCHEMA_VERSION) {
11198
11585
  this.allowTabSynchronization = allowTabSynchronization;
11199
11586
  this.persistenceKey = persistenceKey;
11200
11587
  this.clientId = clientId;
@@ -11203,6 +11590,7 @@ class IndexedDbPersistence {
11203
11590
  this.document = document;
11204
11591
  this.sequenceNumberSyncer = sequenceNumberSyncer;
11205
11592
  this.forceOwningTab = forceOwningTab;
11593
+ this.schemaVersion = schemaVersion;
11206
11594
  this.listenSequence = null;
11207
11595
  this._started = false;
11208
11596
  this.isPrimary = false;
@@ -11224,10 +11612,9 @@ class IndexedDbPersistence {
11224
11612
  this.referenceDelegate = new IndexedDbLruDelegateImpl(this, lruParams);
11225
11613
  this.dbName = persistenceKey + MAIN_DATABASE;
11226
11614
  this.serializer = new LocalSerializer(serializer);
11227
- this.simpleDb = new SimpleDb(this.dbName, SCHEMA_VERSION, new SchemaConverter(this.serializer));
11615
+ this.simpleDb = new SimpleDb(this.dbName, this.schemaVersion, new SchemaConverter(this.serializer));
11228
11616
  this.targetCache = new IndexedDbTargetCache(this.referenceDelegate, this.serializer);
11229
- this.indexManager = new IndexedDbIndexManager();
11230
- this.remoteDocumentCache = newIndexedDbRemoteDocumentCache(this.serializer, this.indexManager);
11617
+ this.remoteDocumentCache = newIndexedDbRemoteDocumentCache(this.serializer);
11231
11618
  this.bundleCache = new IndexedDbBundleCache();
11232
11619
  if (this.window && this.window.localStorage) {
11233
11620
  this.webStorage = this.window.localStorage;
@@ -11563,8 +11950,8 @@ class IndexedDbPersistence {
11563
11950
  get started() {
11564
11951
  return this._started;
11565
11952
  }
11566
- getMutationQueue(user) {
11567
- return IndexedDbMutationQueue.forUser(user, this.serializer, this.indexManager, this.referenceDelegate);
11953
+ getMutationQueue(user, indexManager) {
11954
+ return IndexedDbMutationQueue.forUser(user, this.serializer, indexManager, this.referenceDelegate);
11568
11955
  }
11569
11956
  getTargetCache() {
11570
11957
  return this.targetCache;
@@ -11572,8 +11959,11 @@ class IndexedDbPersistence {
11572
11959
  getRemoteDocumentCache() {
11573
11960
  return this.remoteDocumentCache;
11574
11961
  }
11575
- getIndexManager() {
11576
- return this.indexManager;
11962
+ getIndexManager(user) {
11963
+ return new IndexedDbIndexManager(user);
11964
+ }
11965
+ getDocumentOverlayCache(user) {
11966
+ return IndexedDbDocumentOverlayCache.forUser(this.serializer, user);
11577
11967
  }
11578
11968
  getBundleCache() {
11579
11969
  return this.bundleCache;
@@ -11581,11 +11971,12 @@ class IndexedDbPersistence {
11581
11971
  runTransaction(action, mode, transactionOperation) {
11582
11972
  logDebug(LOG_TAG$d, 'Starting transaction:', action);
11583
11973
  const simpleDbMode = mode === 'readonly' ? 'readonly' : 'readwrite';
11974
+ const objectStores = getObjectStores(this.schemaVersion);
11584
11975
  let persistenceTransaction;
11585
11976
  // Do all transactions as readwrite against all object stores, since we
11586
11977
  // are the only reader/writer.
11587
11978
  return this.simpleDb
11588
- .runTransaction(action, simpleDbMode, ALL_STORES, simpleDbTxn => {
11979
+ .runTransaction(action, simpleDbMode, objectStores, simpleDbTxn => {
11589
11980
  persistenceTransaction = new IndexedDbTransaction(simpleDbTxn, this.listenSequence
11590
11981
  ? this.listenSequence.next()
11591
11982
  : ListenSequence.INVALID);
@@ -11957,39 +12348,28 @@ class LocalDocumentsView {
11957
12348
  getDocumentsMatchingCollectionQuery(transaction, query, sinceReadTime) {
11958
12349
  // Query the remote documents and overlay mutations.
11959
12350
  let results;
11960
- let mutationBatches;
11961
12351
  return this.remoteDocumentCache
11962
- .getDocumentsMatchingQuery(transaction, query, sinceReadTime)
12352
+ .getAll(transaction, query.path, sinceReadTime)
11963
12353
  .next(queryResults => {
11964
12354
  results = queryResults;
11965
12355
  return this.mutationQueue.getAllMutationBatchesAffectingQuery(transaction, query);
11966
12356
  })
11967
- .next(matchingMutationBatches => {
11968
- mutationBatches = matchingMutationBatches;
11969
- // It is possible that a PatchMutation can make a document match a query, even if
11970
- // the version in the RemoteDocumentCache is not a match yet (waiting for server
11971
- // to ack). To handle this, we find all document keys affected by the PatchMutations
11972
- // that are not in `result` yet, and back fill them via `remoteDocumentCache.getEntries`,
11973
- // otherwise those `PatchMutations` will be ignored because no base document can be found,
11974
- // and lead to missing result for the query.
11975
- return this.addMissingBaseDocuments(transaction, mutationBatches, results).next(mergedDocuments => {
11976
- results = mergedDocuments;
11977
- for (const batch of mutationBatches) {
11978
- for (const mutation of batch.mutations) {
11979
- const key = mutation.key;
11980
- let document = results.get(key);
11981
- if (document == null) {
11982
- // Create invalid document to apply mutations on top of
11983
- document = MutableDocument.newInvalidDocument(key);
11984
- results = results.insert(key, document);
11985
- }
11986
- mutationApplyToLocalView(mutation, document, batch.localWriteTime);
11987
- if (!document.isFoundDocument()) {
11988
- results = results.remove(key);
11989
- }
12357
+ .next(mutationBatches => {
12358
+ for (const batch of mutationBatches) {
12359
+ for (const mutation of batch.mutations) {
12360
+ const key = mutation.key;
12361
+ let document = results.get(key);
12362
+ if (document == null) {
12363
+ // Create invalid document to apply mutations on top of
12364
+ document = MutableDocument.newInvalidDocument(key);
12365
+ results = results.insert(key, document);
12366
+ }
12367
+ mutationApplyToLocalView(mutation, document, batch.localWriteTime);
12368
+ if (!document.isFoundDocument()) {
12369
+ results = results.remove(key);
11990
12370
  }
11991
12371
  }
11992
- });
12372
+ }
11993
12373
  })
11994
12374
  .next(() => {
11995
12375
  // Finally, filter out any documents that don't actually match
@@ -12002,29 +12382,6 @@ class LocalDocumentsView {
12002
12382
  return results;
12003
12383
  });
12004
12384
  }
12005
- addMissingBaseDocuments(transaction, matchingMutationBatches, existingDocuments) {
12006
- let missingBaseDocEntriesForPatching = documentKeySet();
12007
- for (const batch of matchingMutationBatches) {
12008
- for (const mutation of batch.mutations) {
12009
- if (mutation instanceof PatchMutation &&
12010
- existingDocuments.get(mutation.key) === null) {
12011
- missingBaseDocEntriesForPatching =
12012
- missingBaseDocEntriesForPatching.add(mutation.key);
12013
- }
12014
- }
12015
- }
12016
- let mergedDocuments = existingDocuments;
12017
- return this.remoteDocumentCache
12018
- .getEntries(transaction, missingBaseDocEntriesForPatching)
12019
- .next(missingBaseDocs => {
12020
- missingBaseDocs.forEach((key, doc) => {
12021
- if (doc.isFoundDocument()) {
12022
- mergedDocuments = mergedDocuments.insert(key, doc);
12023
- }
12024
- });
12025
- return mergedDocuments;
12026
- });
12027
- }
12028
12385
  }
12029
12386
 
12030
12387
  /**
@@ -12083,11 +12440,18 @@ class LocalStoreImpl {
12083
12440
  * PORTING NOTE: This is only used for multi-tab synchronization.
12084
12441
  */
12085
12442
  this.lastDocumentChangeReadTime = SnapshotVersion.min();
12086
- this.mutationQueue = persistence.getMutationQueue(initialUser);
12087
12443
  this.remoteDocuments = persistence.getRemoteDocumentCache();
12088
12444
  this.targetCache = persistence.getTargetCache();
12089
- this.localDocuments = new LocalDocumentsView(this.remoteDocuments, this.mutationQueue, this.persistence.getIndexManager());
12090
12445
  this.bundleCache = persistence.getBundleCache();
12446
+ this.initializeUserComponents(initialUser);
12447
+ }
12448
+ initializeUserComponents(user) {
12449
+ // TODO(indexing): Add spec tests that test these components change after a
12450
+ // user change
12451
+ this.indexManager = this.persistence.getIndexManager(user);
12452
+ this.mutationQueue = this.persistence.getMutationQueue(user, this.indexManager);
12453
+ this.localDocuments = new LocalDocumentsView(this.remoteDocuments, this.mutationQueue, this.indexManager);
12454
+ this.remoteDocuments.setIndexManager(this.indexManager);
12091
12455
  this.queryEngine.setLocalDocumentsView(this.localDocuments);
12092
12456
  }
12093
12457
  collectGarbage(garbageCollector) {
@@ -12109,8 +12473,6 @@ persistence, queryEngine, initialUser, serializer) {
12109
12473
  // change.
12110
12474
  async function localStoreHandleUserChange(localStore, user) {
12111
12475
  const localStoreImpl = debugCast(localStore);
12112
- let newMutationQueue = localStoreImpl.mutationQueue;
12113
- let newLocalDocuments = localStoreImpl.localDocuments;
12114
12476
  const result = await localStoreImpl.persistence.runTransaction('Handle user change', 'readonly', txn => {
12115
12477
  // Swap out the mutation queue, grabbing the pending mutation batches
12116
12478
  // before and after.
@@ -12119,11 +12481,8 @@ async function localStoreHandleUserChange(localStore, user) {
12119
12481
  .getAllMutationBatches(txn)
12120
12482
  .next(promisedOldBatches => {
12121
12483
  oldBatches = promisedOldBatches;
12122
- newMutationQueue = localStoreImpl.persistence.getMutationQueue(user);
12123
- // Recreate our LocalDocumentsView using the new
12124
- // MutationQueue.
12125
- newLocalDocuments = new LocalDocumentsView(localStoreImpl.remoteDocuments, newMutationQueue, localStoreImpl.persistence.getIndexManager());
12126
- return newMutationQueue.getAllMutationBatches(txn);
12484
+ localStoreImpl.initializeUserComponents(user);
12485
+ return localStoreImpl.mutationQueue.getAllMutationBatches(txn);
12127
12486
  })
12128
12487
  .next(newBatches => {
12129
12488
  const removedBatchIds = [];
@@ -12144,7 +12503,7 @@ async function localStoreHandleUserChange(localStore, user) {
12144
12503
  }
12145
12504
  // Return the set of all (potentially) changed documents and the list
12146
12505
  // of mutation batch IDs that were affected by change.
12147
- return newLocalDocuments
12506
+ return localStoreImpl.localDocuments
12148
12507
  .getDocuments(txn, changedKeys)
12149
12508
  .next(affectedDocuments => {
12150
12509
  return {
@@ -12155,9 +12514,6 @@ async function localStoreHandleUserChange(localStore, user) {
12155
12514
  });
12156
12515
  });
12157
12516
  });
12158
- localStoreImpl.mutationQueue = newMutationQueue;
12159
- localStoreImpl.localDocuments = newLocalDocuments;
12160
- localStoreImpl.queryEngine.setLocalDocumentsView(localStoreImpl.localDocuments);
12161
12517
  return result;
12162
12518
  }
12163
12519
  /* Accepts locally generated Mutations and commit them to storage. */
@@ -12870,6 +13226,122 @@ class MemoryBundleCache {
12870
13226
  }
12871
13227
  }
12872
13228
 
13229
+ /**
13230
+ * @license
13231
+ * Copyright 2022 Google LLC
13232
+ *
13233
+ * Licensed under the Apache License, Version 2.0 (the "License");
13234
+ * you may not use this file except in compliance with the License.
13235
+ * You may obtain a copy of the License at
13236
+ *
13237
+ * http://www.apache.org/licenses/LICENSE-2.0
13238
+ *
13239
+ * Unless required by applicable law or agreed to in writing, software
13240
+ * distributed under the License is distributed on an "AS IS" BASIS,
13241
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13242
+ * See the License for the specific language governing permissions and
13243
+ * limitations under the License.
13244
+ */
13245
+ /**
13246
+ * An in-memory implementation of DocumentOverlayCache.
13247
+ */
13248
+ class MemoryDocumentOverlayCache {
13249
+ constructor() {
13250
+ // A map sorted by DocumentKey, whose value is a pair of the largest batch id
13251
+ // for the overlay and the overlay itself.
13252
+ this.overlays = new SortedMap(DocumentKey.comparator);
13253
+ this.overlayByBatchId = new Map();
13254
+ }
13255
+ getOverlay(transaction, key) {
13256
+ return PersistencePromise.resolve(this.overlays.get(key));
13257
+ }
13258
+ saveOverlays(transaction, largestBatchId, overlays) {
13259
+ overlays.forEach(mutation => {
13260
+ this.saveOverlay(transaction, largestBatchId, mutation);
13261
+ });
13262
+ return PersistencePromise.resolve();
13263
+ }
13264
+ removeOverlaysForBatchId(transaction, documentKeys, batchId) {
13265
+ const keys = this.overlayByBatchId.get(batchId);
13266
+ if (keys !== undefined) {
13267
+ keys.forEach(key => (this.overlays = this.overlays.remove(key)));
13268
+ this.overlayByBatchId.delete(batchId);
13269
+ }
13270
+ return PersistencePromise.resolve();
13271
+ }
13272
+ getOverlaysForCollection(transaction, collection, sinceBatchId) {
13273
+ const result = new Map();
13274
+ const immediateChildrenPathLength = collection.length + 1;
13275
+ const prefix = new DocumentKey(collection.child(''));
13276
+ const iter = this.overlays.getIteratorFrom(prefix);
13277
+ while (iter.hasNext()) {
13278
+ const entry = iter.getNext();
13279
+ const overlay = entry.value;
13280
+ const key = overlay.getKey();
13281
+ if (!collection.isPrefixOf(key.path)) {
13282
+ break;
13283
+ }
13284
+ // Documents from sub-collections
13285
+ if (key.path.length !== immediateChildrenPathLength) {
13286
+ continue;
13287
+ }
13288
+ if (overlay.largestBatchId > sinceBatchId) {
13289
+ result.set(overlay.getKey(), overlay);
13290
+ }
13291
+ }
13292
+ return PersistencePromise.resolve(result);
13293
+ }
13294
+ getOverlaysForCollectionGroup(transaction, collectionGroup, sinceBatchId, count) {
13295
+ let batchIdToOverlays = new SortedMap((key1, key2) => key1 - key2);
13296
+ const iter = this.overlays.getIterator();
13297
+ while (iter.hasNext()) {
13298
+ const entry = iter.getNext();
13299
+ const overlay = entry.value;
13300
+ const key = overlay.getKey();
13301
+ if (key.getCollectionGroup() !== collectionGroup) {
13302
+ continue;
13303
+ }
13304
+ if (overlay.largestBatchId > sinceBatchId) {
13305
+ let overlaysForBatchId = batchIdToOverlays.get(overlay.largestBatchId);
13306
+ if (overlaysForBatchId === null) {
13307
+ overlaysForBatchId = new Map();
13308
+ batchIdToOverlays = batchIdToOverlays.insert(overlay.largestBatchId, overlaysForBatchId);
13309
+ }
13310
+ overlaysForBatchId.set(overlay.getKey(), overlay);
13311
+ }
13312
+ }
13313
+ const result = new Map();
13314
+ const batchIter = batchIdToOverlays.getIterator();
13315
+ while (batchIter.hasNext()) {
13316
+ const entry = batchIter.getNext();
13317
+ const overlays = entry.value;
13318
+ overlays.forEach((overlay, key) => result.set(key, overlay));
13319
+ if (result.size >= count) {
13320
+ break;
13321
+ }
13322
+ }
13323
+ return PersistencePromise.resolve(result);
13324
+ }
13325
+ saveOverlay(transaction, largestBatchId, mutation) {
13326
+ if (mutation === null) {
13327
+ return;
13328
+ }
13329
+ // Remove the association of the overlay to its batch id.
13330
+ const existing = this.overlays.get(mutation.key);
13331
+ if (existing !== null) {
13332
+ this.overlayByBatchId.get(existing.largestBatchId).delete(mutation.key);
13333
+ }
13334
+ this.overlays = this.overlays.insert(mutation.key, new Overlay(largestBatchId, mutation));
13335
+ // Create the association of this overlay to the given largestBatchId.
13336
+ let batch = this.overlayByBatchId.get(largestBatchId);
13337
+ if (batch === undefined) {
13338
+ batch = new Set();
13339
+ this.overlayByBatchId.set(largestBatchId, batch);
13340
+ }
13341
+ batch.add(mutation.key);
13342
+ }
13343
+ }
13344
+
12873
13345
  /**
12874
13346
  * @license
12875
13347
  * Copyright 2017 Google LLC
@@ -13223,14 +13695,16 @@ class MemoryRemoteDocumentCacheImpl {
13223
13695
  * expected to just return 0 to avoid unnecessarily doing the work of
13224
13696
  * calculating the size.
13225
13697
  */
13226
- constructor(indexManager, sizer) {
13227
- this.indexManager = indexManager;
13698
+ constructor(sizer) {
13228
13699
  this.sizer = sizer;
13229
13700
  /** Underlying cache of documents and their read times. */
13230
13701
  this.docs = documentEntryMap();
13231
13702
  /** Size of all cached documents. */
13232
13703
  this.size = 0;
13233
13704
  }
13705
+ setIndexManager(indexManager) {
13706
+ this.indexManager = indexManager;
13707
+ }
13234
13708
  /**
13235
13709
  * Adds the supplied entry to the cache and updates the cache size as appropriate.
13236
13710
  *
@@ -13278,21 +13752,22 @@ class MemoryRemoteDocumentCacheImpl {
13278
13752
  });
13279
13753
  return PersistencePromise.resolve(results);
13280
13754
  }
13281
- getDocumentsMatchingQuery(transaction, query, sinceReadTime) {
13755
+ getAll(transaction, collectionPath, sinceReadTime) {
13282
13756
  let results = mutableDocumentMap();
13283
13757
  // Documents are ordered by key, so we can use a prefix scan to narrow down
13284
13758
  // the documents we need to match the query against.
13285
- const prefix = new DocumentKey(query.path.child(''));
13759
+ const prefix = new DocumentKey(collectionPath.child(''));
13286
13760
  const iterator = this.docs.getIteratorFrom(prefix);
13287
13761
  while (iterator.hasNext()) {
13288
13762
  const { key, value: { document } } = iterator.getNext();
13289
- if (!query.path.isPrefixOf(key.path)) {
13763
+ if (!collectionPath.isPrefixOf(key.path)) {
13290
13764
  break;
13291
13765
  }
13292
- if (document.readTime.compareTo(sinceReadTime) <= 0) {
13766
+ if (key.path.length > collectionPath.length + 1) {
13767
+ // Exclude entries from subcollections.
13293
13768
  continue;
13294
13769
  }
13295
- if (!queryMatches(query, document)) {
13770
+ if (document.readTime.compareTo(sinceReadTime) <= 0) {
13296
13771
  continue;
13297
13772
  }
13298
13773
  results = results.insert(document.key, document.mutableCopy());
@@ -13314,13 +13789,12 @@ class MemoryRemoteDocumentCacheImpl {
13314
13789
  /**
13315
13790
  * Creates a new memory-only RemoteDocumentCache.
13316
13791
  *
13317
- * @param indexManager - A class that manages collection group indices.
13318
13792
  * @param sizer - Used to assess the size of a document. For eager GC, this is
13319
13793
  * expected to just return 0 to avoid unnecessarily doing the work of
13320
13794
  * calculating the size.
13321
13795
  */
13322
- function newMemoryRemoteDocumentCache(indexManager, sizer) {
13323
- return new MemoryRemoteDocumentCacheImpl(indexManager, sizer);
13796
+ function newMemoryRemoteDocumentCache(sizer) {
13797
+ return new MemoryRemoteDocumentCacheImpl(sizer);
13324
13798
  }
13325
13799
  /**
13326
13800
  * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.
@@ -13514,6 +13988,7 @@ class MemoryPersistence {
13514
13988
  */
13515
13989
  constructor(referenceDelegateFactory, serializer) {
13516
13990
  this.mutationQueues = {};
13991
+ this.overlays = {};
13517
13992
  this.listenSequence = new ListenSequence(0);
13518
13993
  this._started = false;
13519
13994
  this._started = true;
@@ -13521,7 +13996,7 @@ class MemoryPersistence {
13521
13996
  this.targetCache = new MemoryTargetCache(this);
13522
13997
  const sizer = (doc) => this.referenceDelegate.documentSize(doc);
13523
13998
  this.indexManager = new MemoryIndexManager();
13524
- this.remoteDocumentCache = newMemoryRemoteDocumentCache(this.indexManager, sizer);
13999
+ this.remoteDocumentCache = newMemoryRemoteDocumentCache(sizer);
13525
14000
  this.serializer = new LocalSerializer(serializer);
13526
14001
  this.bundleCache = new MemoryBundleCache(this.serializer);
13527
14002
  }
@@ -13542,13 +14017,23 @@ class MemoryPersistence {
13542
14017
  setNetworkEnabled() {
13543
14018
  // No op.
13544
14019
  }
13545
- getIndexManager() {
14020
+ getIndexManager(user) {
14021
+ // We do not currently support indices for memory persistence, so we can
14022
+ // return the same shared instance of the memory index manager.
13546
14023
  return this.indexManager;
13547
14024
  }
13548
- getMutationQueue(user) {
14025
+ getDocumentOverlayCache(user) {
14026
+ let overlay = this.overlays[user.toKey()];
14027
+ if (!overlay) {
14028
+ overlay = new MemoryDocumentOverlayCache();
14029
+ this.overlays[user.toKey()] = overlay;
14030
+ }
14031
+ return overlay;
14032
+ }
14033
+ getMutationQueue(user, indexManager) {
13549
14034
  let queue = this.mutationQueues[user.toKey()];
13550
14035
  if (!queue) {
13551
- queue = new MemoryMutationQueue(this.indexManager, this.referenceDelegate);
14036
+ queue = new MemoryMutationQueue(indexManager, this.referenceDelegate);
13552
14037
  this.mutationQueues[user.toKey()] = queue;
13553
14038
  }
13554
14039
  return queue;
@@ -20511,12 +20996,12 @@ async function syncEngineListen(syncEngine, query) {
20511
20996
  }
20512
20997
  else {
20513
20998
  const targetData = await localStoreAllocateTarget(syncEngineImpl.localStore, queryToTarget(query));
20514
- const status = syncEngineImpl.sharedClientState.addLocalQueryTarget(targetData.targetId);
20515
- targetId = targetData.targetId;
20516
- viewSnapshot = await initializeViewAndComputeSnapshot(syncEngineImpl, query, targetId, status === 'current');
20517
20999
  if (syncEngineImpl.isPrimaryClient) {
20518
21000
  remoteStoreListen(syncEngineImpl.remoteStore, targetData);
20519
21001
  }
21002
+ const status = syncEngineImpl.sharedClientState.addLocalQueryTarget(targetData.targetId);
21003
+ targetId = targetData.targetId;
21004
+ viewSnapshot = await initializeViewAndComputeSnapshot(syncEngineImpl, query, targetId, status === 'current');
20520
21005
  }
20521
21006
  return viewSnapshot;
20522
21007
  }