@firebase/firestore 3.4.7-canary.e9e5f6b3c → 3.4.8-canary.38da5d9be

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 (57) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/firestore/src/core/target.d.ts +2 -0
  3. package/dist/firestore/src/local/index_manager.d.ts +19 -3
  4. package/dist/firestore/src/local/indexeddb_index_manager.d.ts +3 -2
  5. package/dist/firestore/src/local/indexeddb_remote_document_cache.d.ts +9 -0
  6. package/dist/firestore/src/local/memory_index_manager.d.ts +2 -2
  7. package/dist/firestore/src/local/simple_db.d.ts +2 -0
  8. package/dist/firestore/test/unit/local/test_index_manager.d.ts +2 -2
  9. package/dist/firestore/test/unit/local/test_remote_document_cache.d.ts +0 -4
  10. package/dist/index.esm2017.js +2998 -2965
  11. package/dist/index.esm2017.js.map +1 -1
  12. package/dist/index.esm5.js +3303 -3272
  13. package/dist/index.esm5.js.map +1 -1
  14. package/dist/index.node.cjs.js +1575 -1508
  15. package/dist/index.node.cjs.js.map +1 -1
  16. package/dist/index.node.mjs +1575 -1508
  17. package/dist/index.node.mjs.map +1 -1
  18. package/dist/index.rn.js +3065 -3032
  19. package/dist/index.rn.js.map +1 -1
  20. package/dist/internal.d.ts +20 -3
  21. package/dist/lite/firestore/src/core/target.d.ts +2 -0
  22. package/dist/lite/firestore/src/local/index_manager.d.ts +19 -3
  23. package/dist/lite/firestore/src/local/indexeddb_index_manager.d.ts +3 -2
  24. package/dist/lite/firestore/src/local/indexeddb_remote_document_cache.d.ts +9 -0
  25. package/dist/lite/firestore/src/local/memory_index_manager.d.ts +2 -2
  26. package/dist/lite/firestore/src/local/simple_db.d.ts +2 -0
  27. package/dist/lite/firestore/test/unit/local/test_index_manager.d.ts +2 -2
  28. package/dist/lite/firestore/test/unit/local/test_remote_document_cache.d.ts +0 -4
  29. package/dist/lite/index.browser.esm2017.js +2 -2
  30. package/dist/lite/index.browser.esm2017.js.map +1 -1
  31. package/dist/lite/index.browser.esm5.js +2 -2
  32. package/dist/lite/index.browser.esm5.js.map +1 -1
  33. package/dist/lite/index.node.cjs.js +2 -2
  34. package/dist/lite/index.node.cjs.js.map +1 -1
  35. package/dist/lite/index.node.mjs +2 -2
  36. package/dist/lite/index.node.mjs.map +1 -1
  37. package/dist/lite/index.rn.esm2017.js +1112 -1112
  38. package/dist/lite/index.rn.esm2017.js.map +1 -1
  39. package/dist/lite/packages/firestore/src/core/target.d.ts +2 -0
  40. package/dist/lite/packages/firestore/src/local/index_manager.d.ts +19 -3
  41. package/dist/lite/packages/firestore/src/local/indexeddb_index_manager.d.ts +3 -2
  42. package/dist/lite/packages/firestore/src/local/indexeddb_remote_document_cache.d.ts +9 -0
  43. package/dist/lite/packages/firestore/src/local/memory_index_manager.d.ts +2 -2
  44. package/dist/lite/packages/firestore/src/local/simple_db.d.ts +2 -0
  45. package/dist/lite/packages/firestore/test/unit/local/test_index_manager.d.ts +2 -2
  46. package/dist/lite/packages/firestore/test/unit/local/test_remote_document_cache.d.ts +0 -4
  47. package/dist/packages/firestore/dist/index.esm2017.d.ts +53 -53
  48. package/dist/packages/firestore/src/core/target.d.ts +2 -0
  49. package/dist/packages/firestore/src/local/index_manager.d.ts +19 -3
  50. package/dist/packages/firestore/src/local/indexeddb_index_manager.d.ts +3 -2
  51. package/dist/packages/firestore/src/local/indexeddb_remote_document_cache.d.ts +9 -0
  52. package/dist/packages/firestore/src/local/memory_index_manager.d.ts +2 -2
  53. package/dist/packages/firestore/src/local/simple_db.d.ts +2 -0
  54. package/dist/packages/firestore/test/unit/local/test_index_manager.d.ts +2 -2
  55. package/dist/packages/firestore/test/unit/local/test_remote_document_cache.d.ts +0 -4
  56. package/dist/private.d.ts +20 -3
  57. package/package.json +9 -9
@@ -8,7 +8,7 @@ import * as grpc from '@grpc/grpc-js';
8
8
  import * as protoLoader from '@grpc/proto-loader';
9
9
 
10
10
  const name = "@firebase/firestore";
11
- const version$1 = "3.4.7-canary.e9e5f6b3c";
11
+ const version$1 = "3.4.8-canary.38da5d9be";
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.10-canary.e9e5f6b3c";
64
+ const version = "9.6.11-canary.38da5d9be";
65
65
 
66
66
  /**
67
67
  * @license
@@ -2286,9 +2286,7 @@ class SimpleDbStore {
2286
2286
  cursor.continue(controller.skipToKey);
2287
2287
  }
2288
2288
  };
2289
- }).next(() => {
2290
- return PersistencePromise.waitFor(results);
2291
- });
2289
+ }).next(() => PersistencePromise.waitFor(results));
2292
2290
  }
2293
2291
  options(indexOrRange, range) {
2294
2292
  let indexName = undefined;
@@ -4312,7 +4310,7 @@ function indexOffsetComparator(left, right) {
4312
4310
 
4313
4311
  /**
4314
4312
  * @license
4315
- * Copyright 2019 Google LLC
4313
+ * Copyright 2017 Google LLC
4316
4314
  *
4317
4315
  * Licensed under the Apache License, Version 2.0 (the "License");
4318
4316
  * you may not use this file except in compliance with the License.
@@ -4326,609 +4324,445 @@ function indexOffsetComparator(left, right) {
4326
4324
  * See the License for the specific language governing permissions and
4327
4325
  * limitations under the License.
4328
4326
  */
4329
- // Visible for testing
4330
- class TargetImpl {
4331
- constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
4332
- this.path = path;
4333
- this.collectionGroup = collectionGroup;
4334
- this.orderBy = orderBy;
4335
- this.filters = filters;
4336
- this.limit = limit;
4337
- this.startAt = startAt;
4338
- this.endAt = endAt;
4339
- this.memoizedCanonicalId = null;
4327
+ // An immutable sorted map implementation, based on a Left-leaning Red-Black
4328
+ // tree.
4329
+ class SortedMap {
4330
+ constructor(comparator, root) {
4331
+ this.comparator = comparator;
4332
+ this.root = root ? root : LLRBNode.EMPTY;
4340
4333
  }
4341
- }
4342
- /**
4343
- * Initializes a Target with a path and optional additional query constraints.
4344
- * Path must currently be empty if this is a collection group query.
4345
- *
4346
- * NOTE: you should always construct `Target` from `Query.toTarget` instead of
4347
- * using this factory method, because `Query` provides an implicit `orderBy`
4348
- * property.
4349
- */
4350
- function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
4351
- return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt);
4352
- }
4353
- function canonifyTarget(target) {
4354
- const targetImpl = debugCast(target);
4355
- if (targetImpl.memoizedCanonicalId === null) {
4356
- let str = targetImpl.path.canonicalString();
4357
- if (targetImpl.collectionGroup !== null) {
4358
- str += '|cg:' + targetImpl.collectionGroup;
4359
- }
4360
- str += '|f:';
4361
- str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');
4362
- str += '|ob:';
4363
- str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');
4364
- if (!isNullOrUndefined(targetImpl.limit)) {
4365
- str += '|l:';
4366
- str += targetImpl.limit;
4367
- }
4368
- if (targetImpl.startAt) {
4369
- str += '|lb:';
4370
- str += targetImpl.startAt.inclusive ? 'b:' : 'a:';
4371
- str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');
4372
- }
4373
- if (targetImpl.endAt) {
4374
- str += '|ub:';
4375
- str += targetImpl.endAt.inclusive ? 'a:' : 'b:';
4376
- str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');
4377
- }
4378
- targetImpl.memoizedCanonicalId = str;
4334
+ // Returns a copy of the map, with the specified key/value added or replaced.
4335
+ insert(key, value) {
4336
+ return new SortedMap(this.comparator, this.root
4337
+ .insert(key, value, this.comparator)
4338
+ .copy(null, null, LLRBNode.BLACK, null, null));
4379
4339
  }
4380
- return targetImpl.memoizedCanonicalId;
4381
- }
4382
- function stringifyTarget(target) {
4383
- let str = target.path.canonicalString();
4384
- if (target.collectionGroup !== null) {
4385
- str += ' collectionGroup=' + target.collectionGroup;
4340
+ // Returns a copy of the map, with the specified key removed.
4341
+ remove(key) {
4342
+ return new SortedMap(this.comparator, this.root
4343
+ .remove(key, this.comparator)
4344
+ .copy(null, null, LLRBNode.BLACK, null, null));
4386
4345
  }
4387
- if (target.filters.length > 0) {
4388
- str += `, filters: [${target.filters
4389
- .map(f => stringifyFilter(f))
4390
- .join(', ')}]`;
4346
+ // Returns the value of the node with the given key, or null.
4347
+ get(key) {
4348
+ let node = this.root;
4349
+ while (!node.isEmpty()) {
4350
+ const cmp = this.comparator(key, node.key);
4351
+ if (cmp === 0) {
4352
+ return node.value;
4353
+ }
4354
+ else if (cmp < 0) {
4355
+ node = node.left;
4356
+ }
4357
+ else if (cmp > 0) {
4358
+ node = node.right;
4359
+ }
4360
+ }
4361
+ return null;
4391
4362
  }
4392
- if (!isNullOrUndefined(target.limit)) {
4393
- str += ', limit: ' + target.limit;
4363
+ // Returns the index of the element in this sorted map, or -1 if it doesn't
4364
+ // exist.
4365
+ indexOf(key) {
4366
+ // Number of nodes that were pruned when descending right
4367
+ let prunedNodes = 0;
4368
+ let node = this.root;
4369
+ while (!node.isEmpty()) {
4370
+ const cmp = this.comparator(key, node.key);
4371
+ if (cmp === 0) {
4372
+ return prunedNodes + node.left.size;
4373
+ }
4374
+ else if (cmp < 0) {
4375
+ node = node.left;
4376
+ }
4377
+ else {
4378
+ // Count all nodes left of the node plus the node itself
4379
+ prunedNodes += node.left.size + 1;
4380
+ node = node.right;
4381
+ }
4382
+ }
4383
+ // Node not found
4384
+ return -1;
4394
4385
  }
4395
- if (target.orderBy.length > 0) {
4396
- str += `, orderBy: [${target.orderBy
4397
- .map(o => stringifyOrderBy(o))
4398
- .join(', ')}]`;
4386
+ isEmpty() {
4387
+ return this.root.isEmpty();
4399
4388
  }
4400
- if (target.startAt) {
4401
- str += ', startAt: ';
4402
- str += target.startAt.inclusive ? 'b:' : 'a:';
4403
- str += target.startAt.position.map(p => canonicalId(p)).join(',');
4389
+ // Returns the total number of nodes in the map.
4390
+ get size() {
4391
+ return this.root.size;
4404
4392
  }
4405
- if (target.endAt) {
4406
- str += ', endAt: ';
4407
- str += target.endAt.inclusive ? 'a:' : 'b:';
4408
- str += target.endAt.position.map(p => canonicalId(p)).join(',');
4393
+ // Returns the minimum key in the map.
4394
+ minKey() {
4395
+ return this.root.minKey();
4409
4396
  }
4410
- return `Target(${str})`;
4411
- }
4412
- function targetEquals(left, right) {
4413
- if (left.limit !== right.limit) {
4414
- return false;
4397
+ // Returns the maximum key in the map.
4398
+ maxKey() {
4399
+ return this.root.maxKey();
4415
4400
  }
4416
- if (left.orderBy.length !== right.orderBy.length) {
4417
- return false;
4401
+ // Traverses the map in key order and calls the specified action function
4402
+ // for each key/value pair. If action returns true, traversal is aborted.
4403
+ // Returns the first truthy value returned by action, or the last falsey
4404
+ // value returned by action.
4405
+ inorderTraversal(action) {
4406
+ return this.root.inorderTraversal(action);
4418
4407
  }
4419
- for (let i = 0; i < left.orderBy.length; i++) {
4420
- if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {
4408
+ forEach(fn) {
4409
+ this.inorderTraversal((k, v) => {
4410
+ fn(k, v);
4421
4411
  return false;
4422
- }
4423
- }
4424
- if (left.filters.length !== right.filters.length) {
4425
- return false;
4412
+ });
4426
4413
  }
4427
- for (let i = 0; i < left.filters.length; i++) {
4428
- if (!filterEquals(left.filters[i], right.filters[i])) {
4414
+ toString() {
4415
+ const descriptions = [];
4416
+ this.inorderTraversal((k, v) => {
4417
+ descriptions.push(`${k}:${v}`);
4429
4418
  return false;
4430
- }
4431
- }
4432
- if (left.collectionGroup !== right.collectionGroup) {
4433
- return false;
4419
+ });
4420
+ return `{${descriptions.join(', ')}}`;
4434
4421
  }
4435
- if (!left.path.isEqual(right.path)) {
4436
- return false;
4422
+ // Traverses the map in reverse key order and calls the specified action
4423
+ // function for each key/value pair. If action returns true, traversal is
4424
+ // aborted.
4425
+ // Returns the first truthy value returned by action, or the last falsey
4426
+ // value returned by action.
4427
+ reverseTraversal(action) {
4428
+ return this.root.reverseTraversal(action);
4437
4429
  }
4438
- if (!boundEquals(left.startAt, right.startAt)) {
4439
- return false;
4430
+ // Returns an iterator over the SortedMap.
4431
+ getIterator() {
4432
+ return new SortedMapIterator(this.root, null, this.comparator, false);
4440
4433
  }
4441
- return boundEquals(left.endAt, right.endAt);
4442
- }
4443
- function targetIsDocumentTarget(target) {
4444
- return (DocumentKey.isDocumentKey(target.path) &&
4445
- target.collectionGroup === null &&
4446
- target.filters.length === 0);
4447
- }
4448
- /** Returns the field filters that target the given field path. */
4449
- function targetGetFieldFiltersForPath(target, path) {
4450
- return target.filters.filter(f => f instanceof FieldFilter && f.field.isEqual(path));
4451
- }
4452
- /**
4453
- * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
4454
- * filters. Returns `null` if there are no such filters.
4455
- */
4456
- function targetGetArrayValues(target, fieldIndex) {
4457
- const segment = fieldIndexGetArraySegment(fieldIndex);
4458
- if (segment === undefined) {
4459
- return null;
4434
+ getIteratorFrom(key) {
4435
+ return new SortedMapIterator(this.root, key, this.comparator, false);
4460
4436
  }
4461
- for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
4462
- switch (fieldFilter.op) {
4463
- case "array-contains-any" /* ARRAY_CONTAINS_ANY */:
4464
- return fieldFilter.value.arrayValue.values || [];
4465
- case "array-contains" /* ARRAY_CONTAINS */:
4466
- return [fieldFilter.value];
4467
- // Remaining filters are not array filters.
4468
- }
4437
+ getReverseIterator() {
4438
+ return new SortedMapIterator(this.root, null, this.comparator, true);
4469
4439
  }
4470
- return null;
4471
- }
4472
- /**
4473
- * Returns the list of values that are used in != or NOT_IN filters. Returns
4474
- * `null` if there are no such filters.
4475
- */
4476
- function targetGetNotInValues(target, fieldIndex) {
4477
- const values = new Map();
4478
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
4479
- for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
4480
- switch (fieldFilter.op) {
4481
- case "==" /* EQUAL */:
4482
- case "in" /* IN */:
4483
- // Encode equality prefix, which is encoded in the index value before
4484
- // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
4485
- // `value != 'ab'`).
4486
- values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
4487
- break;
4488
- case "not-in" /* NOT_IN */:
4489
- case "!=" /* NOT_EQUAL */:
4490
- // NotIn/NotEqual is always a suffix. There cannot be any remaining
4491
- // segments and hence we can return early here.
4492
- values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
4493
- return Array.from(values.values());
4494
- // Remaining filters cannot be used as notIn bounds.
4495
- }
4496
- }
4440
+ getReverseIteratorFrom(key) {
4441
+ return new SortedMapIterator(this.root, key, this.comparator, true);
4497
4442
  }
4498
- return null;
4499
- }
4500
- /**
4501
- * Returns a lower bound of field values that can be used as a starting point to
4502
- * scan the index defined by `fieldIndex`. Returns `null` if no lower bound
4503
- * exists.
4504
- */
4505
- function targetGetLowerBound(target, fieldIndex) {
4506
- const values = [];
4507
- let inclusive = true;
4508
- // For each segment, retrieve a lower bound if there is a suitable filter or
4509
- // startAt.
4510
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
4511
- const segmentBound = segment.kind === 0 /* ASCENDING */
4512
- ? targetGetLowerBoundForField(target, segment.fieldPath, target.startAt)
4513
- : targetGetUpperBoundForField(target, segment.fieldPath, target.startAt);
4514
- if (!segmentBound.value) {
4515
- // No lower bound exists
4516
- return null;
4517
- }
4518
- values.push(segmentBound.value);
4519
- inclusive && (inclusive = segmentBound.inclusive);
4520
- }
4521
- return new Bound(values, inclusive);
4522
- }
4523
- /**
4524
- * Returns an upper bound of field values that can be used as an ending point
4525
- * when scanning the index defined by `fieldIndex`. Returns `null` if no
4526
- * upper bound exists.
4527
- */
4528
- function targetGetUpperBound(target, fieldIndex) {
4529
- const values = [];
4530
- let inclusive = true;
4531
- // For each segment, retrieve an upper bound if there is a suitable filter or
4532
- // endAt.
4533
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
4534
- const segmentBound = segment.kind === 0 /* ASCENDING */
4535
- ? targetGetUpperBoundForField(target, segment.fieldPath, target.endAt)
4536
- : targetGetLowerBoundForField(target, segment.fieldPath, target.endAt);
4537
- if (!segmentBound.value) {
4538
- // No upper bound exists
4539
- return null;
4540
- }
4541
- values.push(segmentBound.value);
4542
- inclusive && (inclusive = segmentBound.inclusive);
4543
- }
4544
- return new Bound(values, inclusive);
4545
- }
4546
- /**
4547
- * Returns the value to use as the lower bound for ascending index segment at
4548
- * the provided `fieldPath` (or the upper bound for an descending segment).
4549
- */
4550
- function targetGetLowerBoundForField(target, fieldPath, bound) {
4551
- let value = undefined;
4552
- let inclusive = true;
4553
- // Process all filters to find a value for the current field segment
4554
- for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
4555
- let filterValue = undefined;
4556
- let filterInclusive = true;
4557
- switch (fieldFilter.op) {
4558
- case "<" /* LESS_THAN */:
4559
- case "<=" /* LESS_THAN_OR_EQUAL */:
4560
- filterValue = valuesGetLowerBound(fieldFilter.value);
4561
- break;
4562
- case "==" /* EQUAL */:
4563
- case "in" /* IN */:
4564
- case ">=" /* GREATER_THAN_OR_EQUAL */:
4565
- filterValue = fieldFilter.value;
4566
- break;
4567
- case ">" /* GREATER_THAN */:
4568
- filterValue = fieldFilter.value;
4569
- filterInclusive = false;
4570
- break;
4571
- case "!=" /* NOT_EQUAL */:
4572
- case "not-in" /* NOT_IN */:
4573
- filterValue = MIN_VALUE;
4574
- break;
4575
- // Remaining filters cannot be used as lower bounds.
4576
- }
4577
- if (valuesMax(value, filterValue) === filterValue) {
4578
- value = filterValue;
4579
- inclusive = filterInclusive;
4580
- }
4581
- }
4582
- // If there is an additional bound, compare the values against the existing
4583
- // range to see if we can narrow the scope.
4584
- if (bound !== null) {
4585
- for (let i = 0; i < target.orderBy.length; ++i) {
4586
- const orderBy = target.orderBy[i];
4587
- if (orderBy.field.isEqual(fieldPath)) {
4588
- const cursorValue = bound.position[i];
4589
- if (valuesMax(value, cursorValue) === cursorValue) {
4590
- value = cursorValue;
4591
- inclusive = bound.inclusive;
4443
+ } // end SortedMap
4444
+ // An iterator over an LLRBNode.
4445
+ class SortedMapIterator {
4446
+ constructor(node, startKey, comparator, isReverse) {
4447
+ this.isReverse = isReverse;
4448
+ this.nodeStack = [];
4449
+ let cmp = 1;
4450
+ while (!node.isEmpty()) {
4451
+ cmp = startKey ? comparator(node.key, startKey) : 1;
4452
+ // flip the comparison if we're going in reverse
4453
+ if (startKey && isReverse) {
4454
+ cmp *= -1;
4455
+ }
4456
+ if (cmp < 0) {
4457
+ // This node is less than our start key. ignore it
4458
+ if (this.isReverse) {
4459
+ node = node.left;
4460
+ }
4461
+ else {
4462
+ node = node.right;
4592
4463
  }
4593
- break;
4594
4464
  }
4595
- }
4596
- }
4597
- return { value, inclusive };
4598
- }
4599
- /**
4600
- * Returns the value to use as the upper bound for ascending index segment at
4601
- * the provided `fieldPath` (or the lower bound for an descending segment).
4602
- */
4603
- function targetGetUpperBoundForField(target, fieldPath, bound) {
4604
- let value = undefined;
4605
- let inclusive = true;
4606
- // Process all filters to find a value for the current field segment
4607
- for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
4608
- let filterValue = undefined;
4609
- let filterInclusive = true;
4610
- switch (fieldFilter.op) {
4611
- case ">=" /* GREATER_THAN_OR_EQUAL */:
4612
- case ">" /* GREATER_THAN */:
4613
- filterValue = valuesGetUpperBound(fieldFilter.value);
4614
- filterInclusive = false;
4615
- break;
4616
- case "==" /* EQUAL */:
4617
- case "in" /* IN */:
4618
- case "<=" /* LESS_THAN_OR_EQUAL */:
4619
- filterValue = fieldFilter.value;
4620
- break;
4621
- case "<" /* LESS_THAN */:
4622
- filterValue = fieldFilter.value;
4623
- filterInclusive = false;
4624
- break;
4625
- case "!=" /* NOT_EQUAL */:
4626
- case "not-in" /* NOT_IN */:
4627
- filterValue = MAX_VALUE;
4465
+ else if (cmp === 0) {
4466
+ // This node is exactly equal to our start key. Push it on the stack,
4467
+ // but stop iterating;
4468
+ this.nodeStack.push(node);
4628
4469
  break;
4629
- // Remaining filters cannot be used as upper bounds.
4630
- }
4631
- if (valuesMin(value, filterValue) === filterValue) {
4632
- value = filterValue;
4633
- inclusive = filterInclusive;
4634
- }
4635
- }
4636
- // If there is an additional bound, compare the values against the existing
4637
- // range to see if we can narrow the scope.
4638
- if (bound !== null) {
4639
- for (let i = 0; i < target.orderBy.length; ++i) {
4640
- const orderBy = target.orderBy[i];
4641
- if (orderBy.field.isEqual(fieldPath)) {
4642
- const cursorValue = bound.position[i];
4643
- if (valuesMin(value, cursorValue) === cursorValue) {
4644
- value = cursorValue;
4645
- inclusive = bound.inclusive;
4470
+ }
4471
+ else {
4472
+ // This node is greater than our start key, add it to the stack and move
4473
+ // to the next one
4474
+ this.nodeStack.push(node);
4475
+ if (this.isReverse) {
4476
+ node = node.right;
4477
+ }
4478
+ else {
4479
+ node = node.left;
4646
4480
  }
4647
- break;
4648
4481
  }
4649
4482
  }
4650
4483
  }
4651
- return { value, inclusive };
4652
- }
4653
- class Filter {
4654
- }
4655
- class FieldFilter extends Filter {
4656
- constructor(field, op, value) {
4657
- super();
4658
- this.field = field;
4659
- this.op = op;
4660
- this.value = value;
4661
- }
4662
- /**
4663
- * Creates a filter based on the provided arguments.
4664
- */
4665
- static create(field, op, value) {
4666
- if (field.isKeyField()) {
4667
- if (op === "in" /* IN */ || op === "not-in" /* NOT_IN */) {
4668
- return this.createKeyFieldInFilter(field, op, value);
4669
- }
4670
- else {
4671
- return new KeyFieldFilter(field, op, value);
4484
+ getNext() {
4485
+ let node = this.nodeStack.pop();
4486
+ const result = { key: node.key, value: node.value };
4487
+ if (this.isReverse) {
4488
+ node = node.left;
4489
+ while (!node.isEmpty()) {
4490
+ this.nodeStack.push(node);
4491
+ node = node.right;
4672
4492
  }
4673
4493
  }
4674
- else if (op === "array-contains" /* ARRAY_CONTAINS */) {
4675
- return new ArrayContainsFilter(field, value);
4676
- }
4677
- else if (op === "in" /* IN */) {
4678
- return new InFilter(field, value);
4679
- }
4680
- else if (op === "not-in" /* NOT_IN */) {
4681
- return new NotInFilter(field, value);
4682
- }
4683
- else if (op === "array-contains-any" /* ARRAY_CONTAINS_ANY */) {
4684
- return new ArrayContainsAnyFilter(field, value);
4685
- }
4686
4494
  else {
4687
- return new FieldFilter(field, op, value);
4495
+ node = node.right;
4496
+ while (!node.isEmpty()) {
4497
+ this.nodeStack.push(node);
4498
+ node = node.left;
4499
+ }
4688
4500
  }
4501
+ return result;
4689
4502
  }
4690
- static createKeyFieldInFilter(field, op, value) {
4691
- return op === "in" /* IN */
4692
- ? new KeyFieldInFilter(field, value)
4693
- : new KeyFieldNotInFilter(field, value);
4694
- }
4695
- matches(doc) {
4696
- const other = doc.data.field(this.field);
4697
- // Types do not have to match in NOT_EQUAL filters.
4698
- if (this.op === "!=" /* NOT_EQUAL */) {
4699
- return (other !== null &&
4700
- this.matchesComparison(valueCompare(other, this.value)));
4701
- }
4702
- // Only compare types with matching backend order (such as double and int).
4703
- return (other !== null &&
4704
- typeOrder(this.value) === typeOrder(other) &&
4705
- this.matchesComparison(valueCompare(other, this.value)));
4503
+ hasNext() {
4504
+ return this.nodeStack.length > 0;
4706
4505
  }
4707
- matchesComparison(comparison) {
4708
- switch (this.op) {
4709
- case "<" /* LESS_THAN */:
4710
- return comparison < 0;
4711
- case "<=" /* LESS_THAN_OR_EQUAL */:
4712
- return comparison <= 0;
4713
- case "==" /* EQUAL */:
4714
- return comparison === 0;
4715
- case "!=" /* NOT_EQUAL */:
4716
- return comparison !== 0;
4717
- case ">" /* GREATER_THAN */:
4718
- return comparison > 0;
4719
- case ">=" /* GREATER_THAN_OR_EQUAL */:
4720
- return comparison >= 0;
4721
- default:
4722
- return fail();
4506
+ peek() {
4507
+ if (this.nodeStack.length === 0) {
4508
+ return null;
4723
4509
  }
4510
+ const node = this.nodeStack[this.nodeStack.length - 1];
4511
+ return { key: node.key, value: node.value };
4724
4512
  }
4725
- isInequality() {
4726
- return ([
4727
- "<" /* LESS_THAN */,
4728
- "<=" /* LESS_THAN_OR_EQUAL */,
4729
- ">" /* GREATER_THAN */,
4730
- ">=" /* GREATER_THAN_OR_EQUAL */,
4731
- "!=" /* NOT_EQUAL */,
4732
- "not-in" /* NOT_IN */
4733
- ].indexOf(this.op) >= 0);
4513
+ } // end SortedMapIterator
4514
+ // Represents a node in a Left-leaning Red-Black tree.
4515
+ class LLRBNode {
4516
+ constructor(key, value, color, left, right) {
4517
+ this.key = key;
4518
+ this.value = value;
4519
+ this.color = color != null ? color : LLRBNode.RED;
4520
+ this.left = left != null ? left : LLRBNode.EMPTY;
4521
+ this.right = right != null ? right : LLRBNode.EMPTY;
4522
+ this.size = this.left.size + 1 + this.right.size;
4734
4523
  }
4735
- }
4736
- function canonifyFilter(filter) {
4737
- // TODO(b/29183165): Technically, this won't be unique if two values have
4738
- // the same description, such as the int 3 and the string "3". So we should
4739
- // add the types in here somehow, too.
4740
- return (filter.field.canonicalString() +
4741
- filter.op.toString() +
4742
- canonicalId(filter.value));
4743
- }
4744
- function filterEquals(f1, f2) {
4745
- return (f1.op === f2.op &&
4746
- f1.field.isEqual(f2.field) &&
4747
- valueEquals(f1.value, f2.value));
4748
- }
4749
- /** Returns a debug description for `filter`. */
4750
- function stringifyFilter(filter) {
4751
- return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(filter.value)}`;
4752
- }
4753
- /** Filter that matches on key fields (i.e. '__name__'). */
4754
- class KeyFieldFilter extends FieldFilter {
4755
- constructor(field, op, value) {
4756
- super(field, op, value);
4757
- this.key = DocumentKey.fromName(value.referenceValue);
4524
+ // Returns a copy of the current node, optionally replacing pieces of it.
4525
+ copy(key, value, color, left, right) {
4526
+ 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);
4758
4527
  }
4759
- matches(doc) {
4760
- const comparison = DocumentKey.comparator(doc.key, this.key);
4761
- return this.matchesComparison(comparison);
4528
+ isEmpty() {
4529
+ return false;
4762
4530
  }
4763
- }
4764
- /** Filter that matches on key fields within an array. */
4765
- class KeyFieldInFilter extends FieldFilter {
4766
- constructor(field, value) {
4767
- super(field, "in" /* IN */, value);
4768
- this.keys = extractDocumentKeysFromArrayValue("in" /* IN */, value);
4531
+ // Traverses the tree in key order and calls the specified action function
4532
+ // for each node. If action returns true, traversal is aborted.
4533
+ // Returns the first truthy value returned by action, or the last falsey
4534
+ // value returned by action.
4535
+ inorderTraversal(action) {
4536
+ return (this.left.inorderTraversal(action) ||
4537
+ action(this.key, this.value) ||
4538
+ this.right.inorderTraversal(action));
4769
4539
  }
4770
- matches(doc) {
4771
- return this.keys.some(key => key.isEqual(doc.key));
4540
+ // Traverses the tree in reverse key order and calls the specified action
4541
+ // function for each node. If action returns true, traversal is aborted.
4542
+ // Returns the first truthy value returned by action, or the last falsey
4543
+ // value returned by action.
4544
+ reverseTraversal(action) {
4545
+ return (this.right.reverseTraversal(action) ||
4546
+ action(this.key, this.value) ||
4547
+ this.left.reverseTraversal(action));
4772
4548
  }
4773
- }
4774
- /** Filter that matches on key fields not present within an array. */
4775
- class KeyFieldNotInFilter extends FieldFilter {
4776
- constructor(field, value) {
4777
- super(field, "not-in" /* NOT_IN */, value);
4778
- this.keys = extractDocumentKeysFromArrayValue("not-in" /* NOT_IN */, value);
4549
+ // Returns the minimum node in the tree.
4550
+ min() {
4551
+ if (this.left.isEmpty()) {
4552
+ return this;
4553
+ }
4554
+ else {
4555
+ return this.left.min();
4556
+ }
4779
4557
  }
4780
- matches(doc) {
4781
- return !this.keys.some(key => key.isEqual(doc.key));
4558
+ // Returns the maximum key in the tree.
4559
+ minKey() {
4560
+ return this.min().key;
4782
4561
  }
4783
- }
4784
- function extractDocumentKeysFromArrayValue(op, value) {
4785
- var _a;
4786
- return (((_a = value.arrayValue) === null || _a === void 0 ? void 0 : _a.values) || []).map(v => {
4787
- return DocumentKey.fromName(v.referenceValue);
4788
- });
4789
- }
4790
- /** A Filter that implements the array-contains operator. */
4791
- class ArrayContainsFilter extends FieldFilter {
4792
- constructor(field, value) {
4793
- super(field, "array-contains" /* ARRAY_CONTAINS */, value);
4562
+ // Returns the maximum key in the tree.
4563
+ maxKey() {
4564
+ if (this.right.isEmpty()) {
4565
+ return this.key;
4566
+ }
4567
+ else {
4568
+ return this.right.maxKey();
4569
+ }
4794
4570
  }
4795
- matches(doc) {
4796
- const other = doc.data.field(this.field);
4797
- return isArray(other) && arrayValueContains(other.arrayValue, this.value);
4571
+ // Returns new tree, with the key/value added.
4572
+ insert(key, value, comparator) {
4573
+ let n = this;
4574
+ const cmp = comparator(key, n.key);
4575
+ if (cmp < 0) {
4576
+ n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
4577
+ }
4578
+ else if (cmp === 0) {
4579
+ n = n.copy(null, value, null, null, null);
4580
+ }
4581
+ else {
4582
+ n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
4583
+ }
4584
+ return n.fixUp();
4798
4585
  }
4799
- }
4800
- /** A Filter that implements the IN operator. */
4801
- class InFilter extends FieldFilter {
4802
- constructor(field, value) {
4803
- super(field, "in" /* IN */, value);
4586
+ removeMin() {
4587
+ if (this.left.isEmpty()) {
4588
+ return LLRBNode.EMPTY;
4589
+ }
4590
+ let n = this;
4591
+ if (!n.left.isRed() && !n.left.left.isRed()) {
4592
+ n = n.moveRedLeft();
4593
+ }
4594
+ n = n.copy(null, null, null, n.left.removeMin(), null);
4595
+ return n.fixUp();
4804
4596
  }
4805
- matches(doc) {
4806
- const other = doc.data.field(this.field);
4807
- return other !== null && arrayValueContains(this.value.arrayValue, other);
4597
+ // Returns new tree, with the specified item removed.
4598
+ remove(key, comparator) {
4599
+ let smallest;
4600
+ let n = this;
4601
+ if (comparator(key, n.key) < 0) {
4602
+ if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {
4603
+ n = n.moveRedLeft();
4604
+ }
4605
+ n = n.copy(null, null, null, n.left.remove(key, comparator), null);
4606
+ }
4607
+ else {
4608
+ if (n.left.isRed()) {
4609
+ n = n.rotateRight();
4610
+ }
4611
+ if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {
4612
+ n = n.moveRedRight();
4613
+ }
4614
+ if (comparator(key, n.key) === 0) {
4615
+ if (n.right.isEmpty()) {
4616
+ return LLRBNode.EMPTY;
4617
+ }
4618
+ else {
4619
+ smallest = n.right.min();
4620
+ n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());
4621
+ }
4622
+ }
4623
+ n = n.copy(null, null, null, null, n.right.remove(key, comparator));
4624
+ }
4625
+ return n.fixUp();
4808
4626
  }
4809
- }
4810
- /** A Filter that implements the not-in operator. */
4811
- class NotInFilter extends FieldFilter {
4812
- constructor(field, value) {
4813
- super(field, "not-in" /* NOT_IN */, value);
4627
+ isRed() {
4628
+ return this.color;
4814
4629
  }
4815
- matches(doc) {
4816
- if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) {
4817
- return false;
4630
+ // Returns new tree after performing any needed rotations.
4631
+ fixUp() {
4632
+ let n = this;
4633
+ if (n.right.isRed() && !n.left.isRed()) {
4634
+ n = n.rotateLeft();
4818
4635
  }
4819
- const other = doc.data.field(this.field);
4820
- return other !== null && !arrayValueContains(this.value.arrayValue, other);
4636
+ if (n.left.isRed() && n.left.left.isRed()) {
4637
+ n = n.rotateRight();
4638
+ }
4639
+ if (n.left.isRed() && n.right.isRed()) {
4640
+ n = n.colorFlip();
4641
+ }
4642
+ return n;
4821
4643
  }
4822
- }
4823
- /** A Filter that implements the array-contains-any operator. */
4824
- class ArrayContainsAnyFilter extends FieldFilter {
4825
- constructor(field, value) {
4826
- super(field, "array-contains-any" /* ARRAY_CONTAINS_ANY */, value);
4644
+ moveRedLeft() {
4645
+ let n = this.colorFlip();
4646
+ if (n.right.left.isRed()) {
4647
+ n = n.copy(null, null, null, null, n.right.rotateRight());
4648
+ n = n.rotateLeft();
4649
+ n = n.colorFlip();
4650
+ }
4651
+ return n;
4827
4652
  }
4828
- matches(doc) {
4829
- const other = doc.data.field(this.field);
4830
- if (!isArray(other) || !other.arrayValue.values) {
4831
- return false;
4653
+ moveRedRight() {
4654
+ let n = this.colorFlip();
4655
+ if (n.left.left.isRed()) {
4656
+ n = n.rotateRight();
4657
+ n = n.colorFlip();
4832
4658
  }
4833
- return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val));
4659
+ return n;
4834
4660
  }
4835
- }
4836
- /**
4837
- * Represents a bound of a query.
4838
- *
4839
- * The bound is specified with the given components representing a position and
4840
- * whether it's just before or just after the position (relative to whatever the
4841
- * query order is).
4842
- *
4843
- * The position represents a logical index position for a query. It's a prefix
4844
- * of values for the (potentially implicit) order by clauses of a query.
4845
- *
4846
- * Bound provides a function to determine whether a document comes before or
4847
- * after a bound. This is influenced by whether the position is just before or
4848
- * just after the provided values.
4849
- */
4850
- class Bound {
4851
- constructor(position, inclusive) {
4852
- this.position = position;
4853
- this.inclusive = inclusive;
4661
+ rotateLeft() {
4662
+ const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
4663
+ return this.right.copy(null, null, this.color, nl, null);
4854
4664
  }
4855
- }
4856
- /**
4857
- * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
4858
- */
4859
- class OrderBy {
4860
- constructor(field, dir = "asc" /* ASCENDING */) {
4861
- this.field = field;
4862
- this.dir = dir;
4665
+ rotateRight() {
4666
+ const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
4667
+ return this.left.copy(null, null, this.color, null, nr);
4863
4668
  }
4864
- }
4865
- function canonifyOrderBy(orderBy) {
4866
- // TODO(b/29183165): Make this collision robust.
4867
- return orderBy.field.canonicalString() + orderBy.dir;
4868
- }
4869
- function stringifyOrderBy(orderBy) {
4870
- return `${orderBy.field.canonicalString()} (${orderBy.dir})`;
4871
- }
4872
- function orderByEquals(left, right) {
4873
- return left.dir === right.dir && left.field.isEqual(right.field);
4874
- }
4875
- function boundCompareToDocument(bound, orderBy, doc) {
4876
- let comparison = 0;
4877
- for (let i = 0; i < bound.position.length; i++) {
4878
- const orderByComponent = orderBy[i];
4879
- const component = bound.position[i];
4880
- if (orderByComponent.field.isKeyField()) {
4881
- comparison = DocumentKey.comparator(DocumentKey.fromName(component.referenceValue), doc.key);
4669
+ colorFlip() {
4670
+ const left = this.left.copy(null, null, !this.left.color, null, null);
4671
+ const right = this.right.copy(null, null, !this.right.color, null, null);
4672
+ return this.copy(null, null, !this.color, left, right);
4673
+ }
4674
+ // For testing.
4675
+ checkMaxDepth() {
4676
+ const blackDepth = this.check();
4677
+ if (Math.pow(2.0, blackDepth) <= this.size + 1) {
4678
+ return true;
4882
4679
  }
4883
4680
  else {
4884
- const docValue = doc.data.field(orderByComponent.field);
4885
- comparison = valueCompare(component, docValue);
4681
+ return false;
4886
4682
  }
4887
- if (orderByComponent.dir === "desc" /* DESCENDING */) {
4888
- comparison = comparison * -1;
4683
+ }
4684
+ // In a balanced RB tree, the black-depth (number of black nodes) from root to
4685
+ // leaves is equal on both sides. This function verifies that or asserts.
4686
+ check() {
4687
+ if (this.isRed() && this.left.isRed()) {
4688
+ throw fail();
4889
4689
  }
4890
- if (comparison !== 0) {
4891
- break;
4690
+ if (this.right.isRed()) {
4691
+ throw fail();
4692
+ }
4693
+ const blackDepth = this.left.check();
4694
+ if (blackDepth !== this.right.check()) {
4695
+ throw fail();
4696
+ }
4697
+ else {
4698
+ return blackDepth + (this.isRed() ? 0 : 1);
4892
4699
  }
4893
4700
  }
4894
- return comparison;
4895
- }
4896
- /**
4897
- * Returns true if a document sorts after a bound using the provided sort
4898
- * order.
4899
- */
4900
- function boundSortsAfterDocument(bound, orderBy, doc) {
4901
- const comparison = boundCompareToDocument(bound, orderBy, doc);
4902
- return bound.inclusive ? comparison >= 0 : comparison > 0;
4903
- }
4904
- /**
4905
- * Returns true if a document sorts before a bound using the provided sort
4906
- * order.
4907
- */
4908
- function boundSortsBeforeDocument(bound, orderBy, doc) {
4909
- const comparison = boundCompareToDocument(bound, orderBy, doc);
4910
- return bound.inclusive ? comparison <= 0 : comparison < 0;
4911
- }
4912
- function boundEquals(left, right) {
4913
- if (left === null) {
4914
- return right === null;
4701
+ } // end LLRBNode
4702
+ // Empty node is shared between all LLRB trees.
4703
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4704
+ LLRBNode.EMPTY = null;
4705
+ LLRBNode.RED = true;
4706
+ LLRBNode.BLACK = false;
4707
+ // Represents an empty node (a leaf node in the Red-Black Tree).
4708
+ class LLRBEmptyNode {
4709
+ constructor() {
4710
+ this.size = 0;
4915
4711
  }
4916
- else if (right === null) {
4712
+ get key() {
4713
+ throw fail();
4714
+ }
4715
+ get value() {
4716
+ throw fail();
4717
+ }
4718
+ get color() {
4719
+ throw fail();
4720
+ }
4721
+ get left() {
4722
+ throw fail();
4723
+ }
4724
+ get right() {
4725
+ throw fail();
4726
+ }
4727
+ // Returns a copy of the current node.
4728
+ copy(key, value, color, left, right) {
4729
+ return this;
4730
+ }
4731
+ // Returns a copy of the tree, with the specified key/value added.
4732
+ insert(key, value, comparator) {
4733
+ return new LLRBNode(key, value);
4734
+ }
4735
+ // Returns a copy of the tree, with the specified key removed.
4736
+ remove(key, comparator) {
4737
+ return this;
4738
+ }
4739
+ isEmpty() {
4740
+ return true;
4741
+ }
4742
+ inorderTraversal(action) {
4917
4743
  return false;
4918
4744
  }
4919
- if (left.inclusive !== right.inclusive ||
4920
- left.position.length !== right.position.length) {
4745
+ reverseTraversal(action) {
4921
4746
  return false;
4922
4747
  }
4923
- for (let i = 0; i < left.position.length; i++) {
4924
- const leftPosition = left.position[i];
4925
- const rightPosition = right.position[i];
4926
- if (!valueEquals(leftPosition, rightPosition)) {
4927
- return false;
4928
- }
4748
+ minKey() {
4749
+ return null;
4929
4750
  }
4930
- return true;
4931
- }
4751
+ maxKey() {
4752
+ return null;
4753
+ }
4754
+ isRed() {
4755
+ return false;
4756
+ }
4757
+ // For testing.
4758
+ checkMaxDepth() {
4759
+ return true;
4760
+ }
4761
+ check() {
4762
+ return 0;
4763
+ }
4764
+ } // end LLRBEmptyNode
4765
+ LLRBNode.EMPTY = new LLRBEmptyNode();
4932
4766
 
4933
4767
  /**
4934
4768
  * @license
@@ -4947,325 +4781,223 @@ function boundEquals(left, right) {
4947
4781
  * limitations under the License.
4948
4782
  */
4949
4783
  /**
4950
- * Query encapsulates all the query attributes we support in the SDK. It can
4951
- * be run against the LocalStore, as well as be converted to a `Target` to
4952
- * query the RemoteStore results.
4784
+ * SortedSet is an immutable (copy-on-write) collection that holds elements
4785
+ * in order specified by the provided comparator.
4953
4786
  *
4954
- * Visible for testing.
4787
+ * NOTE: if provided comparator returns 0 for two elements, we consider them to
4788
+ * be equal!
4955
4789
  */
4956
- class QueryImpl {
4957
- /**
4958
- * Initializes a Query with a path and optional additional query constraints.
4959
- * Path must currently be empty if this is a collection group query.
4960
- */
4961
- constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* First */, startAt = null, endAt = null) {
4962
- this.path = path;
4963
- this.collectionGroup = collectionGroup;
4964
- this.explicitOrderBy = explicitOrderBy;
4965
- this.filters = filters;
4966
- this.limit = limit;
4967
- this.limitType = limitType;
4968
- this.startAt = startAt;
4969
- this.endAt = endAt;
4970
- this.memoizedOrderBy = null;
4971
- // The corresponding `Target` of this `Query` instance.
4972
- this.memoizedTarget = null;
4973
- if (this.startAt) ;
4974
- if (this.endAt) ;
4790
+ class SortedSet {
4791
+ constructor(comparator) {
4792
+ this.comparator = comparator;
4793
+ this.data = new SortedMap(this.comparator);
4975
4794
  }
4976
- }
4977
- /** Creates a new Query instance with the options provided. */
4978
- function newQuery(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt) {
4979
- return new QueryImpl(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt);
4980
- }
4981
- /** Creates a new Query for a query that matches all documents at `path` */
4982
- function newQueryForPath(path) {
4983
- return new QueryImpl(path);
4984
- }
4985
- /**
4986
- * Helper to convert a collection group query into a collection query at a
4987
- * specific path. This is used when executing collection group queries, since
4988
- * we have to split the query into a set of collection queries at multiple
4989
- * paths.
4990
- */
4991
- function asCollectionQueryAtPath(query, path) {
4992
- return new QueryImpl(path,
4993
- /*collectionGroup=*/ null, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
4994
- }
4995
- /**
4996
- * Returns true if this query does not specify any query constraints that
4997
- * could remove results.
4998
- */
4999
- function matchesAllDocuments(query) {
5000
- return (query.filters.length === 0 &&
5001
- query.limit === null &&
5002
- query.startAt == null &&
5003
- query.endAt == null &&
5004
- (query.explicitOrderBy.length === 0 ||
5005
- (query.explicitOrderBy.length === 1 &&
5006
- query.explicitOrderBy[0].field.isKeyField())));
5007
- }
5008
- function hasLimitToFirst(query) {
5009
- return !isNullOrUndefined(query.limit) && query.limitType === "F" /* First */;
5010
- }
5011
- function hasLimitToLast(query) {
5012
- return !isNullOrUndefined(query.limit) && query.limitType === "L" /* Last */;
5013
- }
5014
- function getFirstOrderByField(query) {
5015
- return query.explicitOrderBy.length > 0
5016
- ? query.explicitOrderBy[0].field
5017
- : null;
5018
- }
5019
- function getInequalityFilterField(query) {
5020
- for (const filter of query.filters) {
5021
- if (filter.isInequality()) {
5022
- return filter.field;
5023
- }
4795
+ has(elem) {
4796
+ return this.data.get(elem) !== null;
5024
4797
  }
5025
- return null;
5026
- }
5027
- /**
5028
- * Checks if any of the provided Operators are included in the query and
5029
- * returns the first one that is, or null if none are.
5030
- */
5031
- function findFilterOperator(query, operators) {
5032
- for (const filter of query.filters) {
5033
- if (operators.indexOf(filter.op) >= 0) {
5034
- return filter.op;
5035
- }
4798
+ first() {
4799
+ return this.data.minKey();
5036
4800
  }
5037
- return null;
5038
- }
5039
- /**
5040
- * Creates a new Query for a collection group query that matches all documents
5041
- * within the provided collection group.
5042
- */
5043
- function newQueryForCollectionGroup(collectionId) {
5044
- return new QueryImpl(ResourcePath.emptyPath(), collectionId);
5045
- }
5046
- /**
5047
- * Returns whether the query matches a single document by path (rather than a
5048
- * collection).
5049
- */
5050
- function isDocumentQuery$1(query) {
5051
- return (DocumentKey.isDocumentKey(query.path) &&
5052
- query.collectionGroup === null &&
5053
- query.filters.length === 0);
5054
- }
5055
- /**
5056
- * Returns whether the query matches a collection group rather than a specific
5057
- * collection.
5058
- */
5059
- function isCollectionGroupQuery(query) {
5060
- return query.collectionGroup !== null;
5061
- }
5062
- /**
5063
- * Returns the implicit order by constraint that is used to execute the Query,
5064
- * which can be different from the order by constraints the user provided (e.g.
5065
- * the SDK and backend always orders by `__name__`).
5066
- */
5067
- function queryOrderBy(query) {
5068
- const queryImpl = debugCast(query);
5069
- if (queryImpl.memoizedOrderBy === null) {
5070
- queryImpl.memoizedOrderBy = [];
5071
- const inequalityField = getInequalityFilterField(queryImpl);
5072
- const firstOrderByField = getFirstOrderByField(queryImpl);
5073
- if (inequalityField !== null && firstOrderByField === null) {
5074
- // In order to implicitly add key ordering, we must also add the
5075
- // inequality filter field for it to be a valid query.
5076
- // Note that the default inequality field and key ordering is ascending.
5077
- if (!inequalityField.isKeyField()) {
5078
- queryImpl.memoizedOrderBy.push(new OrderBy(inequalityField));
5079
- }
5080
- queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), "asc" /* ASCENDING */));
5081
- }
5082
- else {
5083
- let foundKeyOrdering = false;
5084
- for (const orderBy of queryImpl.explicitOrderBy) {
5085
- queryImpl.memoizedOrderBy.push(orderBy);
5086
- if (orderBy.field.isKeyField()) {
5087
- foundKeyOrdering = true;
5088
- }
5089
- }
5090
- if (!foundKeyOrdering) {
5091
- // The order of the implicit key ordering always matches the last
5092
- // explicit order by
5093
- const lastDirection = queryImpl.explicitOrderBy.length > 0
5094
- ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1]
5095
- .dir
5096
- : "asc" /* ASCENDING */;
5097
- queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection));
4801
+ last() {
4802
+ return this.data.maxKey();
4803
+ }
4804
+ get size() {
4805
+ return this.data.size;
4806
+ }
4807
+ indexOf(elem) {
4808
+ return this.data.indexOf(elem);
4809
+ }
4810
+ /** Iterates elements in order defined by "comparator" */
4811
+ forEach(cb) {
4812
+ this.data.inorderTraversal((k, v) => {
4813
+ cb(k);
4814
+ return false;
4815
+ });
4816
+ }
4817
+ /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
4818
+ forEachInRange(range, cb) {
4819
+ const iter = this.data.getIteratorFrom(range[0]);
4820
+ while (iter.hasNext()) {
4821
+ const elem = iter.getNext();
4822
+ if (this.comparator(elem.key, range[1]) >= 0) {
4823
+ return;
5098
4824
  }
4825
+ cb(elem.key);
5099
4826
  }
5100
4827
  }
5101
- return queryImpl.memoizedOrderBy;
5102
- }
5103
- /**
5104
- * Converts this `Query` instance to it's corresponding `Target` representation.
5105
- */
5106
- function queryToTarget(query) {
5107
- const queryImpl = debugCast(query);
5108
- if (!queryImpl.memoizedTarget) {
5109
- if (queryImpl.limitType === "F" /* First */) {
5110
- queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, queryOrderBy(queryImpl), queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt);
4828
+ /**
4829
+ * Iterates over `elem`s such that: start &lt;= elem until false is returned.
4830
+ */
4831
+ forEachWhile(cb, start) {
4832
+ let iter;
4833
+ if (start !== undefined) {
4834
+ iter = this.data.getIteratorFrom(start);
5111
4835
  }
5112
4836
  else {
5113
- // Flip the orderBy directions since we want the last results
5114
- const orderBys = [];
5115
- for (const orderBy of queryOrderBy(queryImpl)) {
5116
- const dir = orderBy.dir === "desc" /* DESCENDING */
5117
- ? "asc" /* ASCENDING */
5118
- : "desc" /* DESCENDING */;
5119
- orderBys.push(new OrderBy(orderBy.field, dir));
4837
+ iter = this.data.getIterator();
4838
+ }
4839
+ while (iter.hasNext()) {
4840
+ const elem = iter.getNext();
4841
+ const result = cb(elem.key);
4842
+ if (!result) {
4843
+ return;
5120
4844
  }
5121
- // We need to swap the cursors to match the now-flipped query ordering.
5122
- const startAt = queryImpl.endAt
5123
- ? new Bound(queryImpl.endAt.position, !queryImpl.endAt.inclusive)
5124
- : null;
5125
- const endAt = queryImpl.startAt
5126
- ? new Bound(queryImpl.startAt.position, !queryImpl.startAt.inclusive)
5127
- : null;
5128
- // Now return as a LimitType.First query.
5129
- queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt);
5130
4845
  }
5131
4846
  }
5132
- return queryImpl.memoizedTarget;
5133
- }
5134
- function queryWithAddedFilter(query, filter) {
5135
- const newFilters = query.filters.concat([filter]);
5136
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt);
5137
- }
5138
- function queryWithAddedOrderBy(query, orderBy) {
5139
- // TODO(dimond): validate that orderBy does not list the same key twice.
5140
- const newOrderBy = query.explicitOrderBy.concat([orderBy]);
5141
- return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
5142
- }
5143
- function queryWithLimit(query, limit, limitType) {
5144
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt);
5145
- }
5146
- function queryWithStartAt(query, bound) {
5147
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt);
5148
- }
5149
- function queryWithEndAt(query, bound) {
5150
- return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound);
5151
- }
5152
- function queryEquals(left, right) {
5153
- return (targetEquals(queryToTarget(left), queryToTarget(right)) &&
5154
- left.limitType === right.limitType);
5155
- }
5156
- // TODO(b/29183165): This is used to get a unique string from a query to, for
5157
- // example, use as a dictionary key, but the implementation is subject to
5158
- // collisions. Make it collision-free.
5159
- function canonifyQuery(query) {
5160
- return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;
5161
- }
5162
- function stringifyQuery(query) {
5163
- return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${query.limitType})`;
5164
- }
5165
- /** Returns whether `doc` matches the constraints of `query`. */
5166
- function queryMatches(query, doc) {
5167
- return (doc.isFoundDocument() &&
5168
- queryMatchesPathAndCollectionGroup(query, doc) &&
5169
- queryMatchesOrderBy(query, doc) &&
5170
- queryMatchesFilters(query, doc) &&
5171
- queryMatchesBounds(query, doc));
5172
- }
5173
- function queryMatchesPathAndCollectionGroup(query, doc) {
5174
- const docPath = doc.key.path;
5175
- if (query.collectionGroup !== null) {
5176
- // NOTE: this.path is currently always empty since we don't expose Collection
5177
- // Group queries rooted at a document path yet.
5178
- return (doc.key.hasCollectionId(query.collectionGroup) &&
5179
- query.path.isPrefixOf(docPath));
4847
+ /** Finds the least element greater than or equal to `elem`. */
4848
+ firstAfterOrEqual(elem) {
4849
+ const iter = this.data.getIteratorFrom(elem);
4850
+ return iter.hasNext() ? iter.getNext().key : null;
5180
4851
  }
5181
- else if (DocumentKey.isDocumentKey(query.path)) {
5182
- // exact match for document queries
5183
- return query.path.isEqual(docPath);
4852
+ getIterator() {
4853
+ return new SortedSetIterator(this.data.getIterator());
5184
4854
  }
5185
- else {
5186
- // shallow ancestor queries by default
5187
- return query.path.isImmediateParentOf(docPath);
4855
+ getIteratorFrom(key) {
4856
+ return new SortedSetIterator(this.data.getIteratorFrom(key));
5188
4857
  }
5189
- }
5190
- /**
5191
- * A document must have a value for every ordering clause in order to show up
5192
- * in the results.
5193
- */
5194
- function queryMatchesOrderBy(query, doc) {
5195
- for (const orderBy of query.explicitOrderBy) {
5196
- // order by key always matches
5197
- if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {
5198
- return false;
4858
+ /** Inserts or updates an element */
4859
+ add(elem) {
4860
+ return this.copy(this.data.remove(elem).insert(elem, true));
4861
+ }
4862
+ /** Deletes an element */
4863
+ delete(elem) {
4864
+ if (!this.has(elem)) {
4865
+ return this;
5199
4866
  }
4867
+ return this.copy(this.data.remove(elem));
5200
4868
  }
5201
- return true;
5202
- }
5203
- function queryMatchesFilters(query, doc) {
5204
- for (const filter of query.filters) {
5205
- if (!filter.matches(doc)) {
4869
+ isEmpty() {
4870
+ return this.data.isEmpty();
4871
+ }
4872
+ unionWith(other) {
4873
+ let result = this;
4874
+ // Make sure `result` always refers to the larger one of the two sets.
4875
+ if (result.size < other.size) {
4876
+ result = other;
4877
+ other = this;
4878
+ }
4879
+ other.forEach(elem => {
4880
+ result = result.add(elem);
4881
+ });
4882
+ return result;
4883
+ }
4884
+ isEqual(other) {
4885
+ if (!(other instanceof SortedSet)) {
4886
+ return false;
4887
+ }
4888
+ if (this.size !== other.size) {
5206
4889
  return false;
5207
4890
  }
4891
+ const thisIt = this.data.getIterator();
4892
+ const otherIt = other.data.getIterator();
4893
+ while (thisIt.hasNext()) {
4894
+ const thisElem = thisIt.getNext().key;
4895
+ const otherElem = otherIt.getNext().key;
4896
+ if (this.comparator(thisElem, otherElem) !== 0) {
4897
+ return false;
4898
+ }
4899
+ }
4900
+ return true;
4901
+ }
4902
+ toArray() {
4903
+ const res = [];
4904
+ this.forEach(targetId => {
4905
+ res.push(targetId);
4906
+ });
4907
+ return res;
4908
+ }
4909
+ toString() {
4910
+ const result = [];
4911
+ this.forEach(elem => result.push(elem));
4912
+ return 'SortedSet(' + result.toString() + ')';
4913
+ }
4914
+ copy(data) {
4915
+ const result = new SortedSet(this.comparator);
4916
+ result.data = data;
4917
+ return result;
5208
4918
  }
5209
- return true;
5210
4919
  }
5211
- /** Makes sure a document is within the bounds, if provided. */
5212
- function queryMatchesBounds(query, doc) {
5213
- if (query.startAt &&
5214
- !boundSortsBeforeDocument(query.startAt, queryOrderBy(query), doc)) {
5215
- return false;
4920
+ class SortedSetIterator {
4921
+ constructor(iter) {
4922
+ this.iter = iter;
5216
4923
  }
5217
- if (query.endAt &&
5218
- !boundSortsAfterDocument(query.endAt, queryOrderBy(query), doc)) {
5219
- return false;
4924
+ getNext() {
4925
+ return this.iter.getNext().key;
4926
+ }
4927
+ hasNext() {
4928
+ return this.iter.hasNext();
5220
4929
  }
5221
- return true;
5222
4930
  }
5223
4931
  /**
5224
- * Returns the collection group that this query targets.
4932
+ * Compares two sorted sets for equality using their natural ordering. The
4933
+ * method computes the intersection and invokes `onAdd` for every element that
4934
+ * is in `after` but not `before`. `onRemove` is invoked for every element in
4935
+ * `before` but missing from `after`.
5225
4936
  *
5226
- * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab
5227
- * synchronization for query results.
5228
- */
5229
- function queryCollectionGroup(query) {
5230
- return (query.collectionGroup ||
5231
- (query.path.length % 2 === 1
5232
- ? query.path.lastSegment()
5233
- : query.path.get(query.path.length - 2)));
5234
- }
5235
- /**
5236
- * Returns a new comparator function that can be used to compare two documents
5237
- * based on the Query's ordering constraint.
4937
+ * The method creates a copy of both `before` and `after` and runs in O(n log
4938
+ * n), where n is the size of the two lists.
4939
+ *
4940
+ * @param before - The elements that exist in the original set.
4941
+ * @param after - The elements to diff against the original set.
4942
+ * @param comparator - The comparator for the elements in before and after.
4943
+ * @param onAdd - A function to invoke for every element that is part of `
4944
+ * after` but not `before`.
4945
+ * @param onRemove - A function to invoke for every element that is part of
4946
+ * `before` but not `after`.
5238
4947
  */
5239
- function newQueryComparator(query) {
5240
- return (d1, d2) => {
5241
- let comparedOnKeyField = false;
5242
- for (const orderBy of queryOrderBy(query)) {
5243
- const comp = compareDocs(orderBy, d1, d2);
5244
- if (comp !== 0) {
5245
- return comp;
4948
+ function diffSortedSets(before, after, comparator, onAdd, onRemove) {
4949
+ const beforeIt = before.getIterator();
4950
+ const afterIt = after.getIterator();
4951
+ let beforeValue = advanceIterator(beforeIt);
4952
+ let afterValue = advanceIterator(afterIt);
4953
+ // Walk through the two sets at the same time, using the ordering defined by
4954
+ // `comparator`.
4955
+ while (beforeValue || afterValue) {
4956
+ let added = false;
4957
+ let removed = false;
4958
+ if (beforeValue && afterValue) {
4959
+ const cmp = comparator(beforeValue, afterValue);
4960
+ if (cmp < 0) {
4961
+ // The element was removed if the next element in our ordered
4962
+ // walkthrough is only in `before`.
4963
+ removed = true;
4964
+ }
4965
+ else if (cmp > 0) {
4966
+ // The element was added if the next element in our ordered walkthrough
4967
+ // is only in `after`.
4968
+ added = true;
5246
4969
  }
5247
- comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();
5248
4970
  }
5249
- return 0;
5250
- };
5251
- }
5252
- function compareDocs(orderBy, d1, d2) {
5253
- const comparison = orderBy.field.isKeyField()
5254
- ? DocumentKey.comparator(d1.key, d2.key)
5255
- : compareDocumentsByField(orderBy.field, d1, d2);
5256
- switch (orderBy.dir) {
5257
- case "asc" /* ASCENDING */:
5258
- return comparison;
5259
- case "desc" /* DESCENDING */:
5260
- return -1 * comparison;
5261
- default:
5262
- return fail();
4971
+ else if (beforeValue != null) {
4972
+ removed = true;
4973
+ }
4974
+ else {
4975
+ added = true;
4976
+ }
4977
+ if (added) {
4978
+ onAdd(afterValue);
4979
+ afterValue = advanceIterator(afterIt);
4980
+ }
4981
+ else if (removed) {
4982
+ onRemove(beforeValue);
4983
+ beforeValue = advanceIterator(beforeIt);
4984
+ }
4985
+ else {
4986
+ beforeValue = advanceIterator(beforeIt);
4987
+ afterValue = advanceIterator(afterIt);
4988
+ }
5263
4989
  }
4990
+ }
4991
+ /**
4992
+ * Returns the next element from the iterator or `undefined` if none available.
4993
+ */
4994
+ function advanceIterator(it) {
4995
+ return it.hasNext() ? it.getNext() : undefined;
5264
4996
  }
5265
4997
 
5266
4998
  /**
5267
4999
  * @license
5268
- * Copyright 2017 Google LLC
5000
+ * Copyright 2019 Google LLC
5269
5001
  *
5270
5002
  * Licensed under the Apache License, Version 2.0 (the "License");
5271
5003
  * you may not use this file except in compliance with the License.
@@ -5279,785 +5011,1084 @@ function compareDocs(orderBy, d1, d2) {
5279
5011
  * See the License for the specific language governing permissions and
5280
5012
  * limitations under the License.
5281
5013
  */
5014
+ // Visible for testing
5015
+ class TargetImpl {
5016
+ constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
5017
+ this.path = path;
5018
+ this.collectionGroup = collectionGroup;
5019
+ this.orderBy = orderBy;
5020
+ this.filters = filters;
5021
+ this.limit = limit;
5022
+ this.startAt = startAt;
5023
+ this.endAt = endAt;
5024
+ this.memoizedCanonicalId = null;
5025
+ }
5026
+ }
5282
5027
  /**
5283
- * A map implementation that uses objects as keys. Objects must have an
5284
- * associated equals function and must be immutable. Entries in the map are
5285
- * stored together with the key being produced from the mapKeyFn. This map
5286
- * automatically handles collisions of keys.
5028
+ * Initializes a Target with a path and optional additional query constraints.
5029
+ * Path must currently be empty if this is a collection group query.
5030
+ *
5031
+ * NOTE: you should always construct `Target` from `Query.toTarget` instead of
5032
+ * using this factory method, because `Query` provides an implicit `orderBy`
5033
+ * property.
5287
5034
  */
5288
- class ObjectMap {
5289
- constructor(mapKeyFn, equalsFn) {
5290
- this.mapKeyFn = mapKeyFn;
5291
- this.equalsFn = equalsFn;
5292
- /**
5293
- * The inner map for a key/value pair. Due to the possibility of collisions we
5294
- * keep a list of entries that we do a linear search through to find an actual
5295
- * match. Note that collisions should be rare, so we still expect near
5296
- * constant time lookups in practice.
5297
- */
5298
- this.inner = {};
5299
- /** The number of entries stored in the map */
5300
- this.innerSize = 0;
5301
- }
5302
- /** Get a value for this key, or undefined if it does not exist. */
5303
- get(key) {
5304
- const id = this.mapKeyFn(key);
5305
- const matches = this.inner[id];
5306
- if (matches === undefined) {
5307
- return undefined;
5035
+ function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
5036
+ return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt);
5037
+ }
5038
+ function canonifyTarget(target) {
5039
+ const targetImpl = debugCast(target);
5040
+ if (targetImpl.memoizedCanonicalId === null) {
5041
+ let str = targetImpl.path.canonicalString();
5042
+ if (targetImpl.collectionGroup !== null) {
5043
+ str += '|cg:' + targetImpl.collectionGroup;
5308
5044
  }
5309
- for (const [otherKey, value] of matches) {
5310
- if (this.equalsFn(otherKey, key)) {
5311
- return value;
5312
- }
5045
+ str += '|f:';
5046
+ str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');
5047
+ str += '|ob:';
5048
+ str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');
5049
+ if (!isNullOrUndefined(targetImpl.limit)) {
5050
+ str += '|l:';
5051
+ str += targetImpl.limit;
5313
5052
  }
5314
- return undefined;
5315
- }
5316
- has(key) {
5317
- return this.get(key) !== undefined;
5318
- }
5319
- /** Put this key and value in the map. */
5320
- set(key, value) {
5321
- const id = this.mapKeyFn(key);
5322
- const matches = this.inner[id];
5323
- if (matches === undefined) {
5324
- this.inner[id] = [[key, value]];
5325
- this.innerSize++;
5326
- return;
5053
+ if (targetImpl.startAt) {
5054
+ str += '|lb:';
5055
+ str += targetImpl.startAt.inclusive ? 'b:' : 'a:';
5056
+ str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');
5327
5057
  }
5328
- for (let i = 0; i < matches.length; i++) {
5329
- if (this.equalsFn(matches[i][0], key)) {
5330
- // This is updating an existing entry and does not increase `innerSize`.
5331
- matches[i] = [key, value];
5332
- return;
5333
- }
5058
+ if (targetImpl.endAt) {
5059
+ str += '|ub:';
5060
+ str += targetImpl.endAt.inclusive ? 'a:' : 'b:';
5061
+ str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');
5334
5062
  }
5335
- matches.push([key, value]);
5336
- this.innerSize++;
5063
+ targetImpl.memoizedCanonicalId = str;
5337
5064
  }
5338
- /**
5339
- * Remove this key from the map. Returns a boolean if anything was deleted.
5340
- */
5341
- delete(key) {
5342
- const id = this.mapKeyFn(key);
5343
- const matches = this.inner[id];
5344
- if (matches === undefined) {
5065
+ return targetImpl.memoizedCanonicalId;
5066
+ }
5067
+ function stringifyTarget(target) {
5068
+ let str = target.path.canonicalString();
5069
+ if (target.collectionGroup !== null) {
5070
+ str += ' collectionGroup=' + target.collectionGroup;
5071
+ }
5072
+ if (target.filters.length > 0) {
5073
+ str += `, filters: [${target.filters
5074
+ .map(f => stringifyFilter(f))
5075
+ .join(', ')}]`;
5076
+ }
5077
+ if (!isNullOrUndefined(target.limit)) {
5078
+ str += ', limit: ' + target.limit;
5079
+ }
5080
+ if (target.orderBy.length > 0) {
5081
+ str += `, orderBy: [${target.orderBy
5082
+ .map(o => stringifyOrderBy(o))
5083
+ .join(', ')}]`;
5084
+ }
5085
+ if (target.startAt) {
5086
+ str += ', startAt: ';
5087
+ str += target.startAt.inclusive ? 'b:' : 'a:';
5088
+ str += target.startAt.position.map(p => canonicalId(p)).join(',');
5089
+ }
5090
+ if (target.endAt) {
5091
+ str += ', endAt: ';
5092
+ str += target.endAt.inclusive ? 'a:' : 'b:';
5093
+ str += target.endAt.position.map(p => canonicalId(p)).join(',');
5094
+ }
5095
+ return `Target(${str})`;
5096
+ }
5097
+ function targetEquals(left, right) {
5098
+ if (left.limit !== right.limit) {
5099
+ return false;
5100
+ }
5101
+ if (left.orderBy.length !== right.orderBy.length) {
5102
+ return false;
5103
+ }
5104
+ for (let i = 0; i < left.orderBy.length; i++) {
5105
+ if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {
5345
5106
  return false;
5346
5107
  }
5347
- for (let i = 0; i < matches.length; i++) {
5348
- if (this.equalsFn(matches[i][0], key)) {
5349
- if (matches.length === 1) {
5350
- delete this.inner[id];
5351
- }
5352
- else {
5353
- matches.splice(i, 1);
5354
- }
5355
- this.innerSize--;
5356
- return true;
5357
- }
5108
+ }
5109
+ if (left.filters.length !== right.filters.length) {
5110
+ return false;
5111
+ }
5112
+ for (let i = 0; i < left.filters.length; i++) {
5113
+ if (!filterEquals(left.filters[i], right.filters[i])) {
5114
+ return false;
5358
5115
  }
5116
+ }
5117
+ if (left.collectionGroup !== right.collectionGroup) {
5359
5118
  return false;
5360
5119
  }
5361
- forEach(fn) {
5362
- forEach(this.inner, (_, entries) => {
5363
- for (const [k, v] of entries) {
5364
- fn(k, v);
5365
- }
5366
- });
5367
- }
5368
- isEmpty() {
5369
- return isEmpty(this.inner);
5120
+ if (!left.path.isEqual(right.path)) {
5121
+ return false;
5370
5122
  }
5371
- size() {
5372
- return this.innerSize;
5123
+ if (!boundEquals(left.startAt, right.startAt)) {
5124
+ return false;
5373
5125
  }
5374
- }
5375
-
5126
+ return boundEquals(left.endAt, right.endAt);
5127
+ }
5128
+ function targetIsDocumentTarget(target) {
5129
+ return (DocumentKey.isDocumentKey(target.path) &&
5130
+ target.collectionGroup === null &&
5131
+ target.filters.length === 0);
5132
+ }
5133
+ /** Returns the field filters that target the given field path. */
5134
+ function targetGetFieldFiltersForPath(target, path) {
5135
+ return target.filters.filter(f => f instanceof FieldFilter && f.field.isEqual(path));
5136
+ }
5376
5137
  /**
5377
- * @license
5378
- * Copyright 2017 Google LLC
5379
- *
5380
- * Licensed under the Apache License, Version 2.0 (the "License");
5381
- * you may not use this file except in compliance with the License.
5382
- * You may obtain a copy of the License at
5383
- *
5384
- * http://www.apache.org/licenses/LICENSE-2.0
5385
- *
5386
- * Unless required by applicable law or agreed to in writing, software
5387
- * distributed under the License is distributed on an "AS IS" BASIS,
5388
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5389
- * See the License for the specific language governing permissions and
5390
- * limitations under the License.
5138
+ * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
5139
+ * filters. Returns `null` if there are no such filters.
5391
5140
  */
5392
- // An immutable sorted map implementation, based on a Left-leaning Red-Black
5393
- // tree.
5394
- class SortedMap {
5395
- constructor(comparator, root) {
5396
- this.comparator = comparator;
5397
- this.root = root ? root : LLRBNode.EMPTY;
5398
- }
5399
- // Returns a copy of the map, with the specified key/value added or replaced.
5400
- insert(key, value) {
5401
- return new SortedMap(this.comparator, this.root
5402
- .insert(key, value, this.comparator)
5403
- .copy(null, null, LLRBNode.BLACK, null, null));
5404
- }
5405
- // Returns a copy of the map, with the specified key removed.
5406
- remove(key) {
5407
- return new SortedMap(this.comparator, this.root
5408
- .remove(key, this.comparator)
5409
- .copy(null, null, LLRBNode.BLACK, null, null));
5410
- }
5411
- // Returns the value of the node with the given key, or null.
5412
- get(key) {
5413
- let node = this.root;
5414
- while (!node.isEmpty()) {
5415
- const cmp = this.comparator(key, node.key);
5416
- if (cmp === 0) {
5417
- return node.value;
5418
- }
5419
- else if (cmp < 0) {
5420
- node = node.left;
5421
- }
5422
- else if (cmp > 0) {
5423
- node = node.right;
5424
- }
5425
- }
5141
+ function targetGetArrayValues(target, fieldIndex) {
5142
+ const segment = fieldIndexGetArraySegment(fieldIndex);
5143
+ if (segment === undefined) {
5426
5144
  return null;
5427
5145
  }
5428
- // Returns the index of the element in this sorted map, or -1 if it doesn't
5429
- // exist.
5430
- indexOf(key) {
5431
- // Number of nodes that were pruned when descending right
5432
- let prunedNodes = 0;
5433
- let node = this.root;
5434
- while (!node.isEmpty()) {
5435
- const cmp = this.comparator(key, node.key);
5436
- if (cmp === 0) {
5437
- return prunedNodes + node.left.size;
5438
- }
5439
- else if (cmp < 0) {
5440
- node = node.left;
5441
- }
5442
- else {
5443
- // Count all nodes left of the node plus the node itself
5444
- prunedNodes += node.left.size + 1;
5445
- node = node.right;
5446
- }
5146
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
5147
+ switch (fieldFilter.op) {
5148
+ case "array-contains-any" /* ARRAY_CONTAINS_ANY */:
5149
+ return fieldFilter.value.arrayValue.values || [];
5150
+ case "array-contains" /* ARRAY_CONTAINS */:
5151
+ return [fieldFilter.value];
5152
+ // Remaining filters are not array filters.
5447
5153
  }
5448
- // Node not found
5449
- return -1;
5450
5154
  }
5451
- isEmpty() {
5452
- return this.root.isEmpty();
5453
- }
5454
- // Returns the total number of nodes in the map.
5455
- get size() {
5456
- return this.root.size;
5457
- }
5458
- // Returns the minimum key in the map.
5459
- minKey() {
5460
- return this.root.minKey();
5461
- }
5462
- // Returns the maximum key in the map.
5463
- maxKey() {
5464
- return this.root.maxKey();
5465
- }
5466
- // Traverses the map in key order and calls the specified action function
5467
- // for each key/value pair. If action returns true, traversal is aborted.
5468
- // Returns the first truthy value returned by action, or the last falsey
5469
- // value returned by action.
5470
- inorderTraversal(action) {
5471
- return this.root.inorderTraversal(action);
5472
- }
5473
- forEach(fn) {
5474
- this.inorderTraversal((k, v) => {
5475
- fn(k, v);
5476
- return false;
5477
- });
5478
- }
5479
- toString() {
5480
- const descriptions = [];
5481
- this.inorderTraversal((k, v) => {
5482
- descriptions.push(`${k}:${v}`);
5483
- return false;
5484
- });
5485
- return `{${descriptions.join(', ')}}`;
5486
- }
5487
- // Traverses the map in reverse key order and calls the specified action
5488
- // function for each key/value pair. If action returns true, traversal is
5489
- // aborted.
5490
- // Returns the first truthy value returned by action, or the last falsey
5491
- // value returned by action.
5492
- reverseTraversal(action) {
5493
- return this.root.reverseTraversal(action);
5494
- }
5495
- // Returns an iterator over the SortedMap.
5496
- getIterator() {
5497
- return new SortedMapIterator(this.root, null, this.comparator, false);
5498
- }
5499
- getIteratorFrom(key) {
5500
- return new SortedMapIterator(this.root, key, this.comparator, false);
5501
- }
5502
- getReverseIterator() {
5503
- return new SortedMapIterator(this.root, null, this.comparator, true);
5504
- }
5505
- getReverseIteratorFrom(key) {
5506
- return new SortedMapIterator(this.root, key, this.comparator, true);
5507
- }
5508
- } // end SortedMap
5509
- // An iterator over an LLRBNode.
5510
- class SortedMapIterator {
5511
- constructor(node, startKey, comparator, isReverse) {
5512
- this.isReverse = isReverse;
5513
- this.nodeStack = [];
5514
- let cmp = 1;
5515
- while (!node.isEmpty()) {
5516
- cmp = startKey ? comparator(node.key, startKey) : 1;
5517
- // flip the comparison if we're going in reverse
5518
- if (startKey && isReverse) {
5519
- cmp *= -1;
5520
- }
5521
- if (cmp < 0) {
5522
- // This node is less than our start key. ignore it
5523
- if (this.isReverse) {
5524
- node = node.left;
5525
- }
5526
- else {
5527
- node = node.right;
5528
- }
5529
- }
5530
- else if (cmp === 0) {
5531
- // This node is exactly equal to our start key. Push it on the stack,
5532
- // but stop iterating;
5533
- this.nodeStack.push(node);
5534
- break;
5535
- }
5536
- else {
5537
- // This node is greater than our start key, add it to the stack and move
5538
- // to the next one
5539
- this.nodeStack.push(node);
5540
- if (this.isReverse) {
5541
- node = node.right;
5542
- }
5543
- else {
5544
- node = node.left;
5545
- }
5155
+ return null;
5156
+ }
5157
+ /**
5158
+ * Returns the list of values that are used in != or NOT_IN filters. Returns
5159
+ * `null` if there are no such filters.
5160
+ */
5161
+ function targetGetNotInValues(target, fieldIndex) {
5162
+ const values = new Map();
5163
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5164
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
5165
+ switch (fieldFilter.op) {
5166
+ case "==" /* EQUAL */:
5167
+ case "in" /* IN */:
5168
+ // Encode equality prefix, which is encoded in the index value before
5169
+ // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
5170
+ // `value != 'ab'`).
5171
+ values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
5172
+ break;
5173
+ case "not-in" /* NOT_IN */:
5174
+ case "!=" /* NOT_EQUAL */:
5175
+ // NotIn/NotEqual is always a suffix. There cannot be any remaining
5176
+ // segments and hence we can return early here.
5177
+ values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
5178
+ return Array.from(values.values());
5179
+ // Remaining filters cannot be used as notIn bounds.
5546
5180
  }
5547
5181
  }
5548
5182
  }
5549
- getNext() {
5550
- let node = this.nodeStack.pop();
5551
- const result = { key: node.key, value: node.value };
5552
- if (this.isReverse) {
5553
- node = node.left;
5554
- while (!node.isEmpty()) {
5555
- this.nodeStack.push(node);
5556
- node = node.right;
5557
- }
5558
- }
5559
- else {
5560
- node = node.right;
5561
- while (!node.isEmpty()) {
5562
- this.nodeStack.push(node);
5563
- node = node.left;
5564
- }
5183
+ return null;
5184
+ }
5185
+ /**
5186
+ * Returns a lower bound of field values that can be used as a starting point to
5187
+ * scan the index defined by `fieldIndex`. Returns `null` if no lower bound
5188
+ * exists.
5189
+ */
5190
+ function targetGetLowerBound(target, fieldIndex) {
5191
+ const values = [];
5192
+ let inclusive = true;
5193
+ // For each segment, retrieve a lower bound if there is a suitable filter or
5194
+ // startAt.
5195
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5196
+ const segmentBound = segment.kind === 0 /* ASCENDING */
5197
+ ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)
5198
+ : targetGetDescendingBound(target, segment.fieldPath, target.startAt);
5199
+ if (!segmentBound.value) {
5200
+ // No lower bound exists
5201
+ return null;
5565
5202
  }
5566
- return result;
5567
- }
5568
- hasNext() {
5569
- return this.nodeStack.length > 0;
5203
+ values.push(segmentBound.value);
5204
+ inclusive && (inclusive = segmentBound.inclusive);
5570
5205
  }
5571
- peek() {
5572
- if (this.nodeStack.length === 0) {
5206
+ return new Bound(values, inclusive);
5207
+ }
5208
+ /**
5209
+ * Returns an upper bound of field values that can be used as an ending point
5210
+ * when scanning the index defined by `fieldIndex`. Returns `null` if no
5211
+ * upper bound exists.
5212
+ */
5213
+ function targetGetUpperBound(target, fieldIndex) {
5214
+ const values = [];
5215
+ let inclusive = true;
5216
+ // For each segment, retrieve an upper bound if there is a suitable filter or
5217
+ // endAt.
5218
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5219
+ const segmentBound = segment.kind === 0 /* ASCENDING */
5220
+ ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)
5221
+ : targetGetAscendingBound(target, segment.fieldPath, target.endAt);
5222
+ if (!segmentBound.value) {
5223
+ // No upper bound exists
5573
5224
  return null;
5574
5225
  }
5575
- const node = this.nodeStack[this.nodeStack.length - 1];
5576
- return { key: node.key, value: node.value };
5577
- }
5578
- } // end SortedMapIterator
5579
- // Represents a node in a Left-leaning Red-Black tree.
5580
- class LLRBNode {
5581
- constructor(key, value, color, left, right) {
5582
- this.key = key;
5583
- this.value = value;
5584
- this.color = color != null ? color : LLRBNode.RED;
5585
- this.left = left != null ? left : LLRBNode.EMPTY;
5586
- this.right = right != null ? right : LLRBNode.EMPTY;
5587
- this.size = this.left.size + 1 + this.right.size;
5588
- }
5589
- // Returns a copy of the current node, optionally replacing pieces of it.
5590
- copy(key, value, color, left, right) {
5591
- 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);
5592
- }
5593
- isEmpty() {
5594
- return false;
5595
- }
5596
- // Traverses the tree in key order and calls the specified action function
5597
- // for each node. If action returns true, traversal is aborted.
5598
- // Returns the first truthy value returned by action, or the last falsey
5599
- // value returned by action.
5600
- inorderTraversal(action) {
5601
- return (this.left.inorderTraversal(action) ||
5602
- action(this.key, this.value) ||
5603
- this.right.inorderTraversal(action));
5604
- }
5605
- // Traverses the tree in reverse key order and calls the specified action
5606
- // function for each node. If action returns true, traversal is aborted.
5607
- // Returns the first truthy value returned by action, or the last falsey
5608
- // value returned by action.
5609
- reverseTraversal(action) {
5610
- return (this.right.reverseTraversal(action) ||
5611
- action(this.key, this.value) ||
5612
- this.left.reverseTraversal(action));
5226
+ values.push(segmentBound.value);
5227
+ inclusive && (inclusive = segmentBound.inclusive);
5613
5228
  }
5614
- // Returns the minimum node in the tree.
5615
- min() {
5616
- if (this.left.isEmpty()) {
5617
- return this;
5229
+ return new Bound(values, inclusive);
5230
+ }
5231
+ /**
5232
+ * Returns the value to use as the lower bound for ascending index segment at
5233
+ * the provided `fieldPath` (or the upper bound for an descending segment).
5234
+ */
5235
+ function targetGetAscendingBound(target, fieldPath, bound) {
5236
+ let value = undefined;
5237
+ let inclusive = true;
5238
+ // Process all filters to find a value for the current field segment
5239
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
5240
+ let filterValue = undefined;
5241
+ let filterInclusive = true;
5242
+ switch (fieldFilter.op) {
5243
+ case "<" /* LESS_THAN */:
5244
+ case "<=" /* LESS_THAN_OR_EQUAL */:
5245
+ filterValue = valuesGetLowerBound(fieldFilter.value);
5246
+ break;
5247
+ case "==" /* EQUAL */:
5248
+ case "in" /* IN */:
5249
+ case ">=" /* GREATER_THAN_OR_EQUAL */:
5250
+ filterValue = fieldFilter.value;
5251
+ break;
5252
+ case ">" /* GREATER_THAN */:
5253
+ filterValue = fieldFilter.value;
5254
+ filterInclusive = false;
5255
+ break;
5256
+ case "!=" /* NOT_EQUAL */:
5257
+ case "not-in" /* NOT_IN */:
5258
+ filterValue = MIN_VALUE;
5259
+ break;
5260
+ // Remaining filters cannot be used as lower bounds.
5618
5261
  }
5619
- else {
5620
- return this.left.min();
5262
+ if (valuesMax(value, filterValue) === filterValue) {
5263
+ value = filterValue;
5264
+ inclusive = filterInclusive;
5621
5265
  }
5622
5266
  }
5623
- // Returns the maximum key in the tree.
5624
- minKey() {
5625
- return this.min().key;
5267
+ // If there is an additional bound, compare the values against the existing
5268
+ // range to see if we can narrow the scope.
5269
+ if (bound !== null) {
5270
+ for (let i = 0; i < target.orderBy.length; ++i) {
5271
+ const orderBy = target.orderBy[i];
5272
+ if (orderBy.field.isEqual(fieldPath)) {
5273
+ const cursorValue = bound.position[i];
5274
+ if (valuesMax(value, cursorValue) === cursorValue) {
5275
+ value = cursorValue;
5276
+ inclusive = bound.inclusive;
5277
+ }
5278
+ break;
5279
+ }
5280
+ }
5626
5281
  }
5627
- // Returns the maximum key in the tree.
5628
- maxKey() {
5629
- if (this.right.isEmpty()) {
5630
- return this.key;
5282
+ return { value, inclusive };
5283
+ }
5284
+ /**
5285
+ * Returns the value to use as the upper bound for ascending index segment at
5286
+ * the provided `fieldPath` (or the lower bound for a descending segment).
5287
+ */
5288
+ function targetGetDescendingBound(target, fieldPath, bound) {
5289
+ let value = undefined;
5290
+ let inclusive = true;
5291
+ // Process all filters to find a value for the current field segment
5292
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
5293
+ let filterValue = undefined;
5294
+ let filterInclusive = true;
5295
+ switch (fieldFilter.op) {
5296
+ case ">=" /* GREATER_THAN_OR_EQUAL */:
5297
+ case ">" /* GREATER_THAN */:
5298
+ filterValue = valuesGetUpperBound(fieldFilter.value);
5299
+ filterInclusive = false;
5300
+ break;
5301
+ case "==" /* EQUAL */:
5302
+ case "in" /* IN */:
5303
+ case "<=" /* LESS_THAN_OR_EQUAL */:
5304
+ filterValue = fieldFilter.value;
5305
+ break;
5306
+ case "<" /* LESS_THAN */:
5307
+ filterValue = fieldFilter.value;
5308
+ filterInclusive = false;
5309
+ break;
5310
+ case "!=" /* NOT_EQUAL */:
5311
+ case "not-in" /* NOT_IN */:
5312
+ filterValue = MAX_VALUE;
5313
+ break;
5314
+ // Remaining filters cannot be used as upper bounds.
5631
5315
  }
5632
- else {
5633
- return this.right.maxKey();
5316
+ if (valuesMin(value, filterValue) === filterValue) {
5317
+ value = filterValue;
5318
+ inclusive = filterInclusive;
5319
+ }
5320
+ }
5321
+ // If there is an additional bound, compare the values against the existing
5322
+ // range to see if we can narrow the scope.
5323
+ if (bound !== null) {
5324
+ for (let i = 0; i < target.orderBy.length; ++i) {
5325
+ const orderBy = target.orderBy[i];
5326
+ if (orderBy.field.isEqual(fieldPath)) {
5327
+ const cursorValue = bound.position[i];
5328
+ if (valuesMin(value, cursorValue) === cursorValue) {
5329
+ value = cursorValue;
5330
+ inclusive = bound.inclusive;
5331
+ }
5332
+ break;
5333
+ }
5634
5334
  }
5635
5335
  }
5636
- // Returns new tree, with the key/value added.
5637
- insert(key, value, comparator) {
5638
- let n = this;
5639
- const cmp = comparator(key, n.key);
5640
- if (cmp < 0) {
5641
- n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
5336
+ return { value, inclusive };
5337
+ }
5338
+ /** Returns the number of segments of a perfect index for this target. */
5339
+ function targetGetSegmentCount(target) {
5340
+ let fields = new SortedSet(FieldPath$1.comparator);
5341
+ let hasArraySegment = false;
5342
+ for (const filter of target.filters) {
5343
+ // TODO(orquery): Use the flattened filters here
5344
+ const fieldFilter = filter;
5345
+ // __name__ is not an explicit segment of any index, so we don't need to
5346
+ // count it.
5347
+ if (fieldFilter.field.isKeyField()) {
5348
+ continue;
5642
5349
  }
5643
- else if (cmp === 0) {
5644
- n = n.copy(null, value, null, null, null);
5350
+ // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
5351
+ // For instance, it is possible to have an index for "a ARRAY a ASC". Even
5352
+ // though these are on the same field, they should be counted as two
5353
+ // separate segments in an index.
5354
+ if (fieldFilter.op === "array-contains" /* ARRAY_CONTAINS */ ||
5355
+ fieldFilter.op === "array-contains-any" /* ARRAY_CONTAINS_ANY */) {
5356
+ hasArraySegment = true;
5645
5357
  }
5646
5358
  else {
5647
- n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
5359
+ fields = fields.add(fieldFilter.field);
5648
5360
  }
5649
- return n.fixUp();
5650
5361
  }
5651
- removeMin() {
5652
- if (this.left.isEmpty()) {
5653
- return LLRBNode.EMPTY;
5654
- }
5655
- let n = this;
5656
- if (!n.left.isRed() && !n.left.left.isRed()) {
5657
- n = n.moveRedLeft();
5362
+ for (const orderBy of target.orderBy) {
5363
+ // __name__ is not an explicit segment of any index, so we don't need to
5364
+ // count it.
5365
+ if (!orderBy.field.isKeyField()) {
5366
+ fields = fields.add(orderBy.field);
5658
5367
  }
5659
- n = n.copy(null, null, null, n.left.removeMin(), null);
5660
- return n.fixUp();
5661
5368
  }
5662
- // Returns new tree, with the specified item removed.
5663
- remove(key, comparator) {
5664
- let smallest;
5665
- let n = this;
5666
- if (comparator(key, n.key) < 0) {
5667
- if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {
5668
- n = n.moveRedLeft();
5669
- }
5670
- n = n.copy(null, null, null, n.left.remove(key, comparator), null);
5671
- }
5672
- else {
5673
- if (n.left.isRed()) {
5674
- n = n.rotateRight();
5675
- }
5676
- if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {
5677
- n = n.moveRedRight();
5369
+ return fields.size + (hasArraySegment ? 1 : 0);
5370
+ }
5371
+ class Filter {
5372
+ }
5373
+ class FieldFilter extends Filter {
5374
+ constructor(field, op, value) {
5375
+ super();
5376
+ this.field = field;
5377
+ this.op = op;
5378
+ this.value = value;
5379
+ }
5380
+ /**
5381
+ * Creates a filter based on the provided arguments.
5382
+ */
5383
+ static create(field, op, value) {
5384
+ if (field.isKeyField()) {
5385
+ if (op === "in" /* IN */ || op === "not-in" /* NOT_IN */) {
5386
+ return this.createKeyFieldInFilter(field, op, value);
5678
5387
  }
5679
- if (comparator(key, n.key) === 0) {
5680
- if (n.right.isEmpty()) {
5681
- return LLRBNode.EMPTY;
5682
- }
5683
- else {
5684
- smallest = n.right.min();
5685
- n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());
5686
- }
5388
+ else {
5389
+ return new KeyFieldFilter(field, op, value);
5687
5390
  }
5688
- n = n.copy(null, null, null, null, n.right.remove(key, comparator));
5689
5391
  }
5690
- return n.fixUp();
5691
- }
5692
- isRed() {
5693
- return this.color;
5694
- }
5695
- // Returns new tree after performing any needed rotations.
5696
- fixUp() {
5697
- let n = this;
5698
- if (n.right.isRed() && !n.left.isRed()) {
5699
- n = n.rotateLeft();
5392
+ else if (op === "array-contains" /* ARRAY_CONTAINS */) {
5393
+ return new ArrayContainsFilter(field, value);
5700
5394
  }
5701
- if (n.left.isRed() && n.left.left.isRed()) {
5702
- n = n.rotateRight();
5395
+ else if (op === "in" /* IN */) {
5396
+ return new InFilter(field, value);
5703
5397
  }
5704
- if (n.left.isRed() && n.right.isRed()) {
5705
- n = n.colorFlip();
5398
+ else if (op === "not-in" /* NOT_IN */) {
5399
+ return new NotInFilter(field, value);
5400
+ }
5401
+ else if (op === "array-contains-any" /* ARRAY_CONTAINS_ANY */) {
5402
+ return new ArrayContainsAnyFilter(field, value);
5403
+ }
5404
+ else {
5405
+ return new FieldFilter(field, op, value);
5706
5406
  }
5707
- return n;
5708
5407
  }
5709
- moveRedLeft() {
5710
- let n = this.colorFlip();
5711
- if (n.right.left.isRed()) {
5712
- n = n.copy(null, null, null, null, n.right.rotateRight());
5713
- n = n.rotateLeft();
5714
- n = n.colorFlip();
5408
+ static createKeyFieldInFilter(field, op, value) {
5409
+ return op === "in" /* IN */
5410
+ ? new KeyFieldInFilter(field, value)
5411
+ : new KeyFieldNotInFilter(field, value);
5412
+ }
5413
+ matches(doc) {
5414
+ const other = doc.data.field(this.field);
5415
+ // Types do not have to match in NOT_EQUAL filters.
5416
+ if (this.op === "!=" /* NOT_EQUAL */) {
5417
+ return (other !== null &&
5418
+ this.matchesComparison(valueCompare(other, this.value)));
5715
5419
  }
5716
- return n;
5420
+ // Only compare types with matching backend order (such as double and int).
5421
+ return (other !== null &&
5422
+ typeOrder(this.value) === typeOrder(other) &&
5423
+ this.matchesComparison(valueCompare(other, this.value)));
5717
5424
  }
5718
- moveRedRight() {
5719
- let n = this.colorFlip();
5720
- if (n.left.left.isRed()) {
5721
- n = n.rotateRight();
5722
- n = n.colorFlip();
5425
+ matchesComparison(comparison) {
5426
+ switch (this.op) {
5427
+ case "<" /* LESS_THAN */:
5428
+ return comparison < 0;
5429
+ case "<=" /* LESS_THAN_OR_EQUAL */:
5430
+ return comparison <= 0;
5431
+ case "==" /* EQUAL */:
5432
+ return comparison === 0;
5433
+ case "!=" /* NOT_EQUAL */:
5434
+ return comparison !== 0;
5435
+ case ">" /* GREATER_THAN */:
5436
+ return comparison > 0;
5437
+ case ">=" /* GREATER_THAN_OR_EQUAL */:
5438
+ return comparison >= 0;
5439
+ default:
5440
+ return fail();
5723
5441
  }
5724
- return n;
5725
5442
  }
5726
- rotateLeft() {
5727
- const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
5728
- return this.right.copy(null, null, this.color, nl, null);
5443
+ isInequality() {
5444
+ return ([
5445
+ "<" /* LESS_THAN */,
5446
+ "<=" /* LESS_THAN_OR_EQUAL */,
5447
+ ">" /* GREATER_THAN */,
5448
+ ">=" /* GREATER_THAN_OR_EQUAL */,
5449
+ "!=" /* NOT_EQUAL */,
5450
+ "not-in" /* NOT_IN */
5451
+ ].indexOf(this.op) >= 0);
5729
5452
  }
5730
- rotateRight() {
5731
- const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
5732
- return this.left.copy(null, null, this.color, null, nr);
5453
+ }
5454
+ function canonifyFilter(filter) {
5455
+ // TODO(b/29183165): Technically, this won't be unique if two values have
5456
+ // the same description, such as the int 3 and the string "3". So we should
5457
+ // add the types in here somehow, too.
5458
+ return (filter.field.canonicalString() +
5459
+ filter.op.toString() +
5460
+ canonicalId(filter.value));
5461
+ }
5462
+ function filterEquals(f1, f2) {
5463
+ return (f1.op === f2.op &&
5464
+ f1.field.isEqual(f2.field) &&
5465
+ valueEquals(f1.value, f2.value));
5466
+ }
5467
+ /** Returns a debug description for `filter`. */
5468
+ function stringifyFilter(filter) {
5469
+ return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(filter.value)}`;
5470
+ }
5471
+ /** Filter that matches on key fields (i.e. '__name__'). */
5472
+ class KeyFieldFilter extends FieldFilter {
5473
+ constructor(field, op, value) {
5474
+ super(field, op, value);
5475
+ this.key = DocumentKey.fromName(value.referenceValue);
5733
5476
  }
5734
- colorFlip() {
5735
- const left = this.left.copy(null, null, !this.left.color, null, null);
5736
- const right = this.right.copy(null, null, !this.right.color, null, null);
5737
- return this.copy(null, null, !this.color, left, right);
5477
+ matches(doc) {
5478
+ const comparison = DocumentKey.comparator(doc.key, this.key);
5479
+ return this.matchesComparison(comparison);
5738
5480
  }
5739
- // For testing.
5740
- checkMaxDepth() {
5741
- const blackDepth = this.check();
5742
- if (Math.pow(2.0, blackDepth) <= this.size + 1) {
5743
- return true;
5744
- }
5745
- else {
5746
- return false;
5747
- }
5481
+ }
5482
+ /** Filter that matches on key fields within an array. */
5483
+ class KeyFieldInFilter extends FieldFilter {
5484
+ constructor(field, value) {
5485
+ super(field, "in" /* IN */, value);
5486
+ this.keys = extractDocumentKeysFromArrayValue("in" /* IN */, value);
5748
5487
  }
5749
- // In a balanced RB tree, the black-depth (number of black nodes) from root to
5750
- // leaves is equal on both sides. This function verifies that or asserts.
5751
- check() {
5752
- if (this.isRed() && this.left.isRed()) {
5753
- throw fail();
5754
- }
5755
- if (this.right.isRed()) {
5756
- throw fail();
5757
- }
5758
- const blackDepth = this.left.check();
5759
- if (blackDepth !== this.right.check()) {
5760
- throw fail();
5761
- }
5762
- else {
5763
- return blackDepth + (this.isRed() ? 0 : 1);
5764
- }
5488
+ matches(doc) {
5489
+ return this.keys.some(key => key.isEqual(doc.key));
5765
5490
  }
5766
- } // end LLRBNode
5767
- // Empty node is shared between all LLRB trees.
5768
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
5769
- LLRBNode.EMPTY = null;
5770
- LLRBNode.RED = true;
5771
- LLRBNode.BLACK = false;
5772
- // Represents an empty node (a leaf node in the Red-Black Tree).
5773
- class LLRBEmptyNode {
5774
- constructor() {
5775
- this.size = 0;
5491
+ }
5492
+ /** Filter that matches on key fields not present within an array. */
5493
+ class KeyFieldNotInFilter extends FieldFilter {
5494
+ constructor(field, value) {
5495
+ super(field, "not-in" /* NOT_IN */, value);
5496
+ this.keys = extractDocumentKeysFromArrayValue("not-in" /* NOT_IN */, value);
5497
+ }
5498
+ matches(doc) {
5499
+ return !this.keys.some(key => key.isEqual(doc.key));
5500
+ }
5501
+ }
5502
+ function extractDocumentKeysFromArrayValue(op, value) {
5503
+ var _a;
5504
+ return (((_a = value.arrayValue) === null || _a === void 0 ? void 0 : _a.values) || []).map(v => {
5505
+ return DocumentKey.fromName(v.referenceValue);
5506
+ });
5507
+ }
5508
+ /** A Filter that implements the array-contains operator. */
5509
+ class ArrayContainsFilter extends FieldFilter {
5510
+ constructor(field, value) {
5511
+ super(field, "array-contains" /* ARRAY_CONTAINS */, value);
5512
+ }
5513
+ matches(doc) {
5514
+ const other = doc.data.field(this.field);
5515
+ return isArray(other) && arrayValueContains(other.arrayValue, this.value);
5516
+ }
5517
+ }
5518
+ /** A Filter that implements the IN operator. */
5519
+ class InFilter extends FieldFilter {
5520
+ constructor(field, value) {
5521
+ super(field, "in" /* IN */, value);
5776
5522
  }
5777
- get key() {
5778
- throw fail();
5523
+ matches(doc) {
5524
+ const other = doc.data.field(this.field);
5525
+ return other !== null && arrayValueContains(this.value.arrayValue, other);
5779
5526
  }
5780
- get value() {
5781
- throw fail();
5527
+ }
5528
+ /** A Filter that implements the not-in operator. */
5529
+ class NotInFilter extends FieldFilter {
5530
+ constructor(field, value) {
5531
+ super(field, "not-in" /* NOT_IN */, value);
5782
5532
  }
5783
- get color() {
5784
- throw fail();
5533
+ matches(doc) {
5534
+ if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) {
5535
+ return false;
5536
+ }
5537
+ const other = doc.data.field(this.field);
5538
+ return other !== null && !arrayValueContains(this.value.arrayValue, other);
5785
5539
  }
5786
- get left() {
5787
- throw fail();
5540
+ }
5541
+ /** A Filter that implements the array-contains-any operator. */
5542
+ class ArrayContainsAnyFilter extends FieldFilter {
5543
+ constructor(field, value) {
5544
+ super(field, "array-contains-any" /* ARRAY_CONTAINS_ANY */, value);
5788
5545
  }
5789
- get right() {
5790
- throw fail();
5546
+ matches(doc) {
5547
+ const other = doc.data.field(this.field);
5548
+ if (!isArray(other) || !other.arrayValue.values) {
5549
+ return false;
5550
+ }
5551
+ return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val));
5791
5552
  }
5792
- // Returns a copy of the current node.
5793
- copy(key, value, color, left, right) {
5794
- return this;
5553
+ }
5554
+ /**
5555
+ * Represents a bound of a query.
5556
+ *
5557
+ * The bound is specified with the given components representing a position and
5558
+ * whether it's just before or just after the position (relative to whatever the
5559
+ * query order is).
5560
+ *
5561
+ * The position represents a logical index position for a query. It's a prefix
5562
+ * of values for the (potentially implicit) order by clauses of a query.
5563
+ *
5564
+ * Bound provides a function to determine whether a document comes before or
5565
+ * after a bound. This is influenced by whether the position is just before or
5566
+ * just after the provided values.
5567
+ */
5568
+ class Bound {
5569
+ constructor(position, inclusive) {
5570
+ this.position = position;
5571
+ this.inclusive = inclusive;
5795
5572
  }
5796
- // Returns a copy of the tree, with the specified key/value added.
5797
- insert(key, value, comparator) {
5798
- return new LLRBNode(key, value);
5573
+ }
5574
+ /**
5575
+ * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
5576
+ */
5577
+ class OrderBy {
5578
+ constructor(field, dir = "asc" /* ASCENDING */) {
5579
+ this.field = field;
5580
+ this.dir = dir;
5799
5581
  }
5800
- // Returns a copy of the tree, with the specified key removed.
5801
- remove(key, comparator) {
5802
- return this;
5582
+ }
5583
+ function canonifyOrderBy(orderBy) {
5584
+ // TODO(b/29183165): Make this collision robust.
5585
+ return orderBy.field.canonicalString() + orderBy.dir;
5586
+ }
5587
+ function stringifyOrderBy(orderBy) {
5588
+ return `${orderBy.field.canonicalString()} (${orderBy.dir})`;
5589
+ }
5590
+ function orderByEquals(left, right) {
5591
+ return left.dir === right.dir && left.field.isEqual(right.field);
5592
+ }
5593
+ function boundCompareToDocument(bound, orderBy, doc) {
5594
+ let comparison = 0;
5595
+ for (let i = 0; i < bound.position.length; i++) {
5596
+ const orderByComponent = orderBy[i];
5597
+ const component = bound.position[i];
5598
+ if (orderByComponent.field.isKeyField()) {
5599
+ comparison = DocumentKey.comparator(DocumentKey.fromName(component.referenceValue), doc.key);
5600
+ }
5601
+ else {
5602
+ const docValue = doc.data.field(orderByComponent.field);
5603
+ comparison = valueCompare(component, docValue);
5604
+ }
5605
+ if (orderByComponent.dir === "desc" /* DESCENDING */) {
5606
+ comparison = comparison * -1;
5607
+ }
5608
+ if (comparison !== 0) {
5609
+ break;
5610
+ }
5803
5611
  }
5804
- isEmpty() {
5805
- return true;
5612
+ return comparison;
5613
+ }
5614
+ /**
5615
+ * Returns true if a document sorts after a bound using the provided sort
5616
+ * order.
5617
+ */
5618
+ function boundSortsAfterDocument(bound, orderBy, doc) {
5619
+ const comparison = boundCompareToDocument(bound, orderBy, doc);
5620
+ return bound.inclusive ? comparison >= 0 : comparison > 0;
5621
+ }
5622
+ /**
5623
+ * Returns true if a document sorts before a bound using the provided sort
5624
+ * order.
5625
+ */
5626
+ function boundSortsBeforeDocument(bound, orderBy, doc) {
5627
+ const comparison = boundCompareToDocument(bound, orderBy, doc);
5628
+ return bound.inclusive ? comparison <= 0 : comparison < 0;
5629
+ }
5630
+ function boundEquals(left, right) {
5631
+ if (left === null) {
5632
+ return right === null;
5806
5633
  }
5807
- inorderTraversal(action) {
5634
+ else if (right === null) {
5808
5635
  return false;
5809
5636
  }
5810
- reverseTraversal(action) {
5637
+ if (left.inclusive !== right.inclusive ||
5638
+ left.position.length !== right.position.length) {
5811
5639
  return false;
5812
5640
  }
5813
- minKey() {
5814
- return null;
5815
- }
5816
- maxKey() {
5817
- return null;
5641
+ for (let i = 0; i < left.position.length; i++) {
5642
+ const leftPosition = left.position[i];
5643
+ const rightPosition = right.position[i];
5644
+ if (!valueEquals(leftPosition, rightPosition)) {
5645
+ return false;
5646
+ }
5818
5647
  }
5819
- isRed() {
5820
- return false;
5648
+ return true;
5649
+ }
5650
+
5651
+ /**
5652
+ * @license
5653
+ * Copyright 2017 Google LLC
5654
+ *
5655
+ * Licensed under the Apache License, Version 2.0 (the "License");
5656
+ * you may not use this file except in compliance with the License.
5657
+ * You may obtain a copy of the License at
5658
+ *
5659
+ * http://www.apache.org/licenses/LICENSE-2.0
5660
+ *
5661
+ * Unless required by applicable law or agreed to in writing, software
5662
+ * distributed under the License is distributed on an "AS IS" BASIS,
5663
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5664
+ * See the License for the specific language governing permissions and
5665
+ * limitations under the License.
5666
+ */
5667
+ /**
5668
+ * Query encapsulates all the query attributes we support in the SDK. It can
5669
+ * be run against the LocalStore, as well as be converted to a `Target` to
5670
+ * query the RemoteStore results.
5671
+ *
5672
+ * Visible for testing.
5673
+ */
5674
+ class QueryImpl {
5675
+ /**
5676
+ * Initializes a Query with a path and optional additional query constraints.
5677
+ * Path must currently be empty if this is a collection group query.
5678
+ */
5679
+ constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* First */, startAt = null, endAt = null) {
5680
+ this.path = path;
5681
+ this.collectionGroup = collectionGroup;
5682
+ this.explicitOrderBy = explicitOrderBy;
5683
+ this.filters = filters;
5684
+ this.limit = limit;
5685
+ this.limitType = limitType;
5686
+ this.startAt = startAt;
5687
+ this.endAt = endAt;
5688
+ this.memoizedOrderBy = null;
5689
+ // The corresponding `Target` of this `Query` instance.
5690
+ this.memoizedTarget = null;
5691
+ if (this.startAt) ;
5692
+ if (this.endAt) ;
5821
5693
  }
5822
- // For testing.
5823
- checkMaxDepth() {
5824
- return true;
5694
+ }
5695
+ /** Creates a new Query instance with the options provided. */
5696
+ function newQuery(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt) {
5697
+ return new QueryImpl(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt);
5698
+ }
5699
+ /** Creates a new Query for a query that matches all documents at `path` */
5700
+ function newQueryForPath(path) {
5701
+ return new QueryImpl(path);
5702
+ }
5703
+ /**
5704
+ * Helper to convert a collection group query into a collection query at a
5705
+ * specific path. This is used when executing collection group queries, since
5706
+ * we have to split the query into a set of collection queries at multiple
5707
+ * paths.
5708
+ */
5709
+ function asCollectionQueryAtPath(query, path) {
5710
+ return new QueryImpl(path,
5711
+ /*collectionGroup=*/ null, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
5712
+ }
5713
+ /**
5714
+ * Returns true if this query does not specify any query constraints that
5715
+ * could remove results.
5716
+ */
5717
+ function matchesAllDocuments(query) {
5718
+ return (query.filters.length === 0 &&
5719
+ query.limit === null &&
5720
+ query.startAt == null &&
5721
+ query.endAt == null &&
5722
+ (query.explicitOrderBy.length === 0 ||
5723
+ (query.explicitOrderBy.length === 1 &&
5724
+ query.explicitOrderBy[0].field.isKeyField())));
5725
+ }
5726
+ function hasLimitToFirst(query) {
5727
+ return !isNullOrUndefined(query.limit) && query.limitType === "F" /* First */;
5728
+ }
5729
+ function hasLimitToLast(query) {
5730
+ return !isNullOrUndefined(query.limit) && query.limitType === "L" /* Last */;
5731
+ }
5732
+ function getFirstOrderByField(query) {
5733
+ return query.explicitOrderBy.length > 0
5734
+ ? query.explicitOrderBy[0].field
5735
+ : null;
5736
+ }
5737
+ function getInequalityFilterField(query) {
5738
+ for (const filter of query.filters) {
5739
+ if (filter.isInequality()) {
5740
+ return filter.field;
5741
+ }
5825
5742
  }
5826
- check() {
5827
- return 0;
5743
+ return null;
5744
+ }
5745
+ /**
5746
+ * Checks if any of the provided Operators are included in the query and
5747
+ * returns the first one that is, or null if none are.
5748
+ */
5749
+ function findFilterOperator(query, operators) {
5750
+ for (const filter of query.filters) {
5751
+ if (operators.indexOf(filter.op) >= 0) {
5752
+ return filter.op;
5753
+ }
5828
5754
  }
5829
- } // end LLRBEmptyNode
5830
- LLRBNode.EMPTY = new LLRBEmptyNode();
5831
-
5755
+ return null;
5756
+ }
5832
5757
  /**
5833
- * @license
5834
- * Copyright 2017 Google LLC
5835
- *
5836
- * Licensed under the Apache License, Version 2.0 (the "License");
5837
- * you may not use this file except in compliance with the License.
5838
- * You may obtain a copy of the License at
5839
- *
5840
- * http://www.apache.org/licenses/LICENSE-2.0
5841
- *
5842
- * Unless required by applicable law or agreed to in writing, software
5843
- * distributed under the License is distributed on an "AS IS" BASIS,
5844
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5845
- * See the License for the specific language governing permissions and
5846
- * limitations under the License.
5758
+ * Creates a new Query for a collection group query that matches all documents
5759
+ * within the provided collection group.
5847
5760
  */
5761
+ function newQueryForCollectionGroup(collectionId) {
5762
+ return new QueryImpl(ResourcePath.emptyPath(), collectionId);
5763
+ }
5848
5764
  /**
5849
- * SortedSet is an immutable (copy-on-write) collection that holds elements
5850
- * in order specified by the provided comparator.
5851
- *
5852
- * NOTE: if provided comparator returns 0 for two elements, we consider them to
5853
- * be equal!
5765
+ * Returns whether the query matches a single document by path (rather than a
5766
+ * collection).
5854
5767
  */
5855
- class SortedSet {
5856
- constructor(comparator) {
5857
- this.comparator = comparator;
5858
- this.data = new SortedMap(this.comparator);
5859
- }
5860
- has(elem) {
5861
- return this.data.get(elem) !== null;
5862
- }
5863
- first() {
5864
- return this.data.minKey();
5865
- }
5866
- last() {
5867
- return this.data.maxKey();
5868
- }
5869
- get size() {
5870
- return this.data.size;
5871
- }
5872
- indexOf(elem) {
5873
- return this.data.indexOf(elem);
5874
- }
5875
- /** Iterates elements in order defined by "comparator" */
5876
- forEach(cb) {
5877
- this.data.inorderTraversal((k, v) => {
5878
- cb(k);
5879
- return false;
5880
- });
5881
- }
5882
- /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */
5883
- forEachInRange(range, cb) {
5884
- const iter = this.data.getIteratorFrom(range[0]);
5885
- while (iter.hasNext()) {
5886
- const elem = iter.getNext();
5887
- if (this.comparator(elem.key, range[1]) >= 0) {
5888
- return;
5768
+ function isDocumentQuery$1(query) {
5769
+ return (DocumentKey.isDocumentKey(query.path) &&
5770
+ query.collectionGroup === null &&
5771
+ query.filters.length === 0);
5772
+ }
5773
+ /**
5774
+ * Returns whether the query matches a collection group rather than a specific
5775
+ * collection.
5776
+ */
5777
+ function isCollectionGroupQuery(query) {
5778
+ return query.collectionGroup !== null;
5779
+ }
5780
+ /**
5781
+ * Returns the implicit order by constraint that is used to execute the Query,
5782
+ * which can be different from the order by constraints the user provided (e.g.
5783
+ * the SDK and backend always orders by `__name__`).
5784
+ */
5785
+ function queryOrderBy(query) {
5786
+ const queryImpl = debugCast(query);
5787
+ if (queryImpl.memoizedOrderBy === null) {
5788
+ queryImpl.memoizedOrderBy = [];
5789
+ const inequalityField = getInequalityFilterField(queryImpl);
5790
+ const firstOrderByField = getFirstOrderByField(queryImpl);
5791
+ if (inequalityField !== null && firstOrderByField === null) {
5792
+ // In order to implicitly add key ordering, we must also add the
5793
+ // inequality filter field for it to be a valid query.
5794
+ // Note that the default inequality field and key ordering is ascending.
5795
+ if (!inequalityField.isKeyField()) {
5796
+ queryImpl.memoizedOrderBy.push(new OrderBy(inequalityField));
5889
5797
  }
5890
- cb(elem.key);
5891
- }
5892
- }
5893
- /**
5894
- * Iterates over `elem`s such that: start &lt;= elem until false is returned.
5895
- */
5896
- forEachWhile(cb, start) {
5897
- let iter;
5898
- if (start !== undefined) {
5899
- iter = this.data.getIteratorFrom(start);
5798
+ queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), "asc" /* ASCENDING */));
5900
5799
  }
5901
5800
  else {
5902
- iter = this.data.getIterator();
5903
- }
5904
- while (iter.hasNext()) {
5905
- const elem = iter.getNext();
5906
- const result = cb(elem.key);
5907
- if (!result) {
5908
- return;
5801
+ let foundKeyOrdering = false;
5802
+ for (const orderBy of queryImpl.explicitOrderBy) {
5803
+ queryImpl.memoizedOrderBy.push(orderBy);
5804
+ if (orderBy.field.isKeyField()) {
5805
+ foundKeyOrdering = true;
5806
+ }
5807
+ }
5808
+ if (!foundKeyOrdering) {
5809
+ // The order of the implicit key ordering always matches the last
5810
+ // explicit order by
5811
+ const lastDirection = queryImpl.explicitOrderBy.length > 0
5812
+ ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1]
5813
+ .dir
5814
+ : "asc" /* ASCENDING */;
5815
+ queryImpl.memoizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection));
5909
5816
  }
5910
5817
  }
5911
5818
  }
5912
- /** Finds the least element greater than or equal to `elem`. */
5913
- firstAfterOrEqual(elem) {
5914
- const iter = this.data.getIteratorFrom(elem);
5915
- return iter.hasNext() ? iter.getNext().key : null;
5916
- }
5917
- getIterator() {
5918
- return new SortedSetIterator(this.data.getIterator());
5919
- }
5920
- getIteratorFrom(key) {
5921
- return new SortedSetIterator(this.data.getIteratorFrom(key));
5922
- }
5923
- /** Inserts or updates an element */
5924
- add(elem) {
5925
- return this.copy(this.data.remove(elem).insert(elem, true));
5926
- }
5927
- /** Deletes an element */
5928
- delete(elem) {
5929
- if (!this.has(elem)) {
5930
- return this;
5931
- }
5932
- return this.copy(this.data.remove(elem));
5933
- }
5934
- isEmpty() {
5935
- return this.data.isEmpty();
5936
- }
5937
- unionWith(other) {
5938
- let result = this;
5939
- // Make sure `result` always refers to the larger one of the two sets.
5940
- if (result.size < other.size) {
5941
- result = other;
5942
- other = this;
5943
- }
5944
- other.forEach(elem => {
5945
- result = result.add(elem);
5946
- });
5947
- return result;
5948
- }
5949
- isEqual(other) {
5950
- if (!(other instanceof SortedSet)) {
5951
- return false;
5952
- }
5953
- if (this.size !== other.size) {
5954
- return false;
5819
+ return queryImpl.memoizedOrderBy;
5820
+ }
5821
+ /**
5822
+ * Converts this `Query` instance to it's corresponding `Target` representation.
5823
+ */
5824
+ function queryToTarget(query) {
5825
+ const queryImpl = debugCast(query);
5826
+ if (!queryImpl.memoizedTarget) {
5827
+ if (queryImpl.limitType === "F" /* First */) {
5828
+ queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, queryOrderBy(queryImpl), queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt);
5955
5829
  }
5956
- const thisIt = this.data.getIterator();
5957
- const otherIt = other.data.getIterator();
5958
- while (thisIt.hasNext()) {
5959
- const thisElem = thisIt.getNext().key;
5960
- const otherElem = otherIt.getNext().key;
5961
- if (this.comparator(thisElem, otherElem) !== 0) {
5962
- return false;
5830
+ else {
5831
+ // Flip the orderBy directions since we want the last results
5832
+ const orderBys = [];
5833
+ for (const orderBy of queryOrderBy(queryImpl)) {
5834
+ const dir = orderBy.dir === "desc" /* DESCENDING */
5835
+ ? "asc" /* ASCENDING */
5836
+ : "desc" /* DESCENDING */;
5837
+ orderBys.push(new OrderBy(orderBy.field, dir));
5963
5838
  }
5839
+ // We need to swap the cursors to match the now-flipped query ordering.
5840
+ const startAt = queryImpl.endAt
5841
+ ? new Bound(queryImpl.endAt.position, !queryImpl.endAt.inclusive)
5842
+ : null;
5843
+ const endAt = queryImpl.startAt
5844
+ ? new Bound(queryImpl.startAt.position, !queryImpl.startAt.inclusive)
5845
+ : null;
5846
+ // Now return as a LimitType.First query.
5847
+ queryImpl.memoizedTarget = newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt);
5964
5848
  }
5965
- return true;
5966
5849
  }
5967
- toArray() {
5968
- const res = [];
5969
- this.forEach(targetId => {
5970
- res.push(targetId);
5971
- });
5972
- return res;
5850
+ return queryImpl.memoizedTarget;
5851
+ }
5852
+ function queryWithAddedFilter(query, filter) {
5853
+ const newFilters = query.filters.concat([filter]);
5854
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt);
5855
+ }
5856
+ function queryWithAddedOrderBy(query, orderBy) {
5857
+ // TODO(dimond): validate that orderBy does not list the same key twice.
5858
+ const newOrderBy = query.explicitOrderBy.concat([orderBy]);
5859
+ return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);
5860
+ }
5861
+ function queryWithLimit(query, limit, limitType) {
5862
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt);
5863
+ }
5864
+ function queryWithStartAt(query, bound) {
5865
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt);
5866
+ }
5867
+ function queryWithEndAt(query, bound) {
5868
+ return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound);
5869
+ }
5870
+ function queryEquals(left, right) {
5871
+ return (targetEquals(queryToTarget(left), queryToTarget(right)) &&
5872
+ left.limitType === right.limitType);
5873
+ }
5874
+ // TODO(b/29183165): This is used to get a unique string from a query to, for
5875
+ // example, use as a dictionary key, but the implementation is subject to
5876
+ // collisions. Make it collision-free.
5877
+ function canonifyQuery(query) {
5878
+ return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`;
5879
+ }
5880
+ function stringifyQuery(query) {
5881
+ return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${query.limitType})`;
5882
+ }
5883
+ /** Returns whether `doc` matches the constraints of `query`. */
5884
+ function queryMatches(query, doc) {
5885
+ return (doc.isFoundDocument() &&
5886
+ queryMatchesPathAndCollectionGroup(query, doc) &&
5887
+ queryMatchesOrderBy(query, doc) &&
5888
+ queryMatchesFilters(query, doc) &&
5889
+ queryMatchesBounds(query, doc));
5890
+ }
5891
+ function queryMatchesPathAndCollectionGroup(query, doc) {
5892
+ const docPath = doc.key.path;
5893
+ if (query.collectionGroup !== null) {
5894
+ // NOTE: this.path is currently always empty since we don't expose Collection
5895
+ // Group queries rooted at a document path yet.
5896
+ return (doc.key.hasCollectionId(query.collectionGroup) &&
5897
+ query.path.isPrefixOf(docPath));
5898
+ }
5899
+ else if (DocumentKey.isDocumentKey(query.path)) {
5900
+ // exact match for document queries
5901
+ return query.path.isEqual(docPath);
5973
5902
  }
5974
- toString() {
5975
- const result = [];
5976
- this.forEach(elem => result.push(elem));
5977
- return 'SortedSet(' + result.toString() + ')';
5903
+ else {
5904
+ // shallow ancestor queries by default
5905
+ return query.path.isImmediateParentOf(docPath);
5978
5906
  }
5979
- copy(data) {
5980
- const result = new SortedSet(this.comparator);
5981
- result.data = data;
5982
- return result;
5907
+ }
5908
+ /**
5909
+ * A document must have a value for every ordering clause in order to show up
5910
+ * in the results.
5911
+ */
5912
+ function queryMatchesOrderBy(query, doc) {
5913
+ for (const orderBy of query.explicitOrderBy) {
5914
+ // order by key always matches
5915
+ if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {
5916
+ return false;
5917
+ }
5983
5918
  }
5919
+ return true;
5984
5920
  }
5985
- class SortedSetIterator {
5986
- constructor(iter) {
5987
- this.iter = iter;
5921
+ function queryMatchesFilters(query, doc) {
5922
+ for (const filter of query.filters) {
5923
+ if (!filter.matches(doc)) {
5924
+ return false;
5925
+ }
5988
5926
  }
5989
- getNext() {
5990
- return this.iter.getNext().key;
5927
+ return true;
5928
+ }
5929
+ /** Makes sure a document is within the bounds, if provided. */
5930
+ function queryMatchesBounds(query, doc) {
5931
+ if (query.startAt &&
5932
+ !boundSortsBeforeDocument(query.startAt, queryOrderBy(query), doc)) {
5933
+ return false;
5991
5934
  }
5992
- hasNext() {
5993
- return this.iter.hasNext();
5935
+ if (query.endAt &&
5936
+ !boundSortsAfterDocument(query.endAt, queryOrderBy(query), doc)) {
5937
+ return false;
5994
5938
  }
5939
+ return true;
5995
5940
  }
5996
5941
  /**
5997
- * Compares two sorted sets for equality using their natural ordering. The
5998
- * method computes the intersection and invokes `onAdd` for every element that
5999
- * is in `after` but not `before`. `onRemove` is invoked for every element in
6000
- * `before` but missing from `after`.
6001
- *
6002
- * The method creates a copy of both `before` and `after` and runs in O(n log
6003
- * n), where n is the size of the two lists.
5942
+ * Returns the collection group that this query targets.
6004
5943
  *
6005
- * @param before - The elements that exist in the original set.
6006
- * @param after - The elements to diff against the original set.
6007
- * @param comparator - The comparator for the elements in before and after.
6008
- * @param onAdd - A function to invoke for every element that is part of `
6009
- * after` but not `before`.
6010
- * @param onRemove - A function to invoke for every element that is part of
6011
- * `before` but not `after`.
5944
+ * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab
5945
+ * synchronization for query results.
6012
5946
  */
6013
- function diffSortedSets(before, after, comparator, onAdd, onRemove) {
6014
- const beforeIt = before.getIterator();
6015
- const afterIt = after.getIterator();
6016
- let beforeValue = advanceIterator(beforeIt);
6017
- let afterValue = advanceIterator(afterIt);
6018
- // Walk through the two sets at the same time, using the ordering defined by
6019
- // `comparator`.
6020
- while (beforeValue || afterValue) {
6021
- let added = false;
6022
- let removed = false;
6023
- if (beforeValue && afterValue) {
6024
- const cmp = comparator(beforeValue, afterValue);
6025
- if (cmp < 0) {
6026
- // The element was removed if the next element in our ordered
6027
- // walkthrough is only in `before`.
6028
- removed = true;
6029
- }
6030
- else if (cmp > 0) {
6031
- // The element was added if the next element in our ordered walkthrough
6032
- // is only in `after`.
6033
- added = true;
5947
+ function queryCollectionGroup(query) {
5948
+ return (query.collectionGroup ||
5949
+ (query.path.length % 2 === 1
5950
+ ? query.path.lastSegment()
5951
+ : query.path.get(query.path.length - 2)));
5952
+ }
5953
+ /**
5954
+ * Returns a new comparator function that can be used to compare two documents
5955
+ * based on the Query's ordering constraint.
5956
+ */
5957
+ function newQueryComparator(query) {
5958
+ return (d1, d2) => {
5959
+ let comparedOnKeyField = false;
5960
+ for (const orderBy of queryOrderBy(query)) {
5961
+ const comp = compareDocs(orderBy, d1, d2);
5962
+ if (comp !== 0) {
5963
+ return comp;
6034
5964
  }
5965
+ comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();
6035
5966
  }
6036
- else if (beforeValue != null) {
6037
- removed = true;
5967
+ return 0;
5968
+ };
5969
+ }
5970
+ function compareDocs(orderBy, d1, d2) {
5971
+ const comparison = orderBy.field.isKeyField()
5972
+ ? DocumentKey.comparator(d1.key, d2.key)
5973
+ : compareDocumentsByField(orderBy.field, d1, d2);
5974
+ switch (orderBy.dir) {
5975
+ case "asc" /* ASCENDING */:
5976
+ return comparison;
5977
+ case "desc" /* DESCENDING */:
5978
+ return -1 * comparison;
5979
+ default:
5980
+ return fail();
5981
+ }
5982
+ }
5983
+
5984
+ /**
5985
+ * @license
5986
+ * Copyright 2017 Google LLC
5987
+ *
5988
+ * Licensed under the Apache License, Version 2.0 (the "License");
5989
+ * you may not use this file except in compliance with the License.
5990
+ * You may obtain a copy of the License at
5991
+ *
5992
+ * http://www.apache.org/licenses/LICENSE-2.0
5993
+ *
5994
+ * Unless required by applicable law or agreed to in writing, software
5995
+ * distributed under the License is distributed on an "AS IS" BASIS,
5996
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5997
+ * See the License for the specific language governing permissions and
5998
+ * limitations under the License.
5999
+ */
6000
+ /**
6001
+ * A map implementation that uses objects as keys. Objects must have an
6002
+ * associated equals function and must be immutable. Entries in the map are
6003
+ * stored together with the key being produced from the mapKeyFn. This map
6004
+ * automatically handles collisions of keys.
6005
+ */
6006
+ class ObjectMap {
6007
+ constructor(mapKeyFn, equalsFn) {
6008
+ this.mapKeyFn = mapKeyFn;
6009
+ this.equalsFn = equalsFn;
6010
+ /**
6011
+ * The inner map for a key/value pair. Due to the possibility of collisions we
6012
+ * keep a list of entries that we do a linear search through to find an actual
6013
+ * match. Note that collisions should be rare, so we still expect near
6014
+ * constant time lookups in practice.
6015
+ */
6016
+ this.inner = {};
6017
+ /** The number of entries stored in the map */
6018
+ this.innerSize = 0;
6019
+ }
6020
+ /** Get a value for this key, or undefined if it does not exist. */
6021
+ get(key) {
6022
+ const id = this.mapKeyFn(key);
6023
+ const matches = this.inner[id];
6024
+ if (matches === undefined) {
6025
+ return undefined;
6038
6026
  }
6039
- else {
6040
- added = true;
6027
+ for (const [otherKey, value] of matches) {
6028
+ if (this.equalsFn(otherKey, key)) {
6029
+ return value;
6030
+ }
6041
6031
  }
6042
- if (added) {
6043
- onAdd(afterValue);
6044
- afterValue = advanceIterator(afterIt);
6032
+ return undefined;
6033
+ }
6034
+ has(key) {
6035
+ return this.get(key) !== undefined;
6036
+ }
6037
+ /** Put this key and value in the map. */
6038
+ set(key, value) {
6039
+ const id = this.mapKeyFn(key);
6040
+ const matches = this.inner[id];
6041
+ if (matches === undefined) {
6042
+ this.inner[id] = [[key, value]];
6043
+ this.innerSize++;
6044
+ return;
6045
6045
  }
6046
- else if (removed) {
6047
- onRemove(beforeValue);
6048
- beforeValue = advanceIterator(beforeIt);
6046
+ for (let i = 0; i < matches.length; i++) {
6047
+ if (this.equalsFn(matches[i][0], key)) {
6048
+ // This is updating an existing entry and does not increase `innerSize`.
6049
+ matches[i] = [key, value];
6050
+ return;
6051
+ }
6049
6052
  }
6050
- else {
6051
- beforeValue = advanceIterator(beforeIt);
6052
- afterValue = advanceIterator(afterIt);
6053
+ matches.push([key, value]);
6054
+ this.innerSize++;
6055
+ }
6056
+ /**
6057
+ * Remove this key from the map. Returns a boolean if anything was deleted.
6058
+ */
6059
+ delete(key) {
6060
+ const id = this.mapKeyFn(key);
6061
+ const matches = this.inner[id];
6062
+ if (matches === undefined) {
6063
+ return false;
6064
+ }
6065
+ for (let i = 0; i < matches.length; i++) {
6066
+ if (this.equalsFn(matches[i][0], key)) {
6067
+ if (matches.length === 1) {
6068
+ delete this.inner[id];
6069
+ }
6070
+ else {
6071
+ matches.splice(i, 1);
6072
+ }
6073
+ this.innerSize--;
6074
+ return true;
6075
+ }
6053
6076
  }
6077
+ return false;
6078
+ }
6079
+ forEach(fn) {
6080
+ forEach(this.inner, (_, entries) => {
6081
+ for (const [k, v] of entries) {
6082
+ fn(k, v);
6083
+ }
6084
+ });
6085
+ }
6086
+ isEmpty() {
6087
+ return isEmpty(this.inner);
6088
+ }
6089
+ size() {
6090
+ return this.innerSize;
6054
6091
  }
6055
- }
6056
- /**
6057
- * Returns the next element from the iterator or `undefined` if none available.
6058
- */
6059
- function advanceIterator(it) {
6060
- return it.hasNext() ? it.getNext() : undefined;
6061
6092
  }
6062
6093
 
6063
6094
  /**
@@ -9975,9 +10006,9 @@ class MemoryIndexManager {
9975
10006
  // Field indices are not supported with memory persistence.
9976
10007
  return PersistencePromise.resolve(null);
9977
10008
  }
9978
- getFieldIndex(transaction, target) {
10009
+ getIndexType(transaction, target) {
9979
10010
  // Field indices are not supported with memory persistence.
9980
- return PersistencePromise.resolve(null);
10011
+ return PersistencePromise.resolve(0 /* NONE */);
9981
10012
  }
9982
10013
  getFieldIndexes(transaction, collectionGroup) {
9983
10014
  // Field indices are not supported with memory persistence.
@@ -10242,10 +10273,27 @@ class IndexedDbIndexManager {
10242
10273
  ? target.collectionGroup
10243
10274
  : target.path.lastSegment();
10244
10275
  return this.getFieldIndexes(transaction, collectionGroup).next(indexes => {
10245
- const matchingIndexes = indexes.filter(i => targetIndexMatcher.servedByIndex(i));
10246
- // Return the index that matches the most number of segments.
10247
- matchingIndexes.sort((l, r) => r.fields.length - l.fields.length);
10248
- return matchingIndexes.length > 0 ? matchingIndexes[0] : null;
10276
+ // Return the index with the most number of segments.
10277
+ let index = null;
10278
+ for (const candidate of indexes) {
10279
+ const matches = targetIndexMatcher.servedByIndex(candidate);
10280
+ if (matches &&
10281
+ (!index || candidate.fields.length > index.fields.length)) {
10282
+ index = candidate;
10283
+ }
10284
+ }
10285
+ return index;
10286
+ });
10287
+ }
10288
+ getIndexType(transaction, target) {
10289
+ // TODO(orqueries): We should look at the subtargets here
10290
+ return this.getFieldIndex(transaction, target).next(index => {
10291
+ if (!index) {
10292
+ return 0 /* NONE */;
10293
+ }
10294
+ return index.fields.length < targetGetSegmentCount(target)
10295
+ ? 1 /* PARTIAL */
10296
+ : 2 /* FULL */;
10249
10297
  });
10250
10298
  }
10251
10299
  /**
@@ -12302,12 +12350,31 @@ function dbCollectionGroupKey(collectionGroup, offset) {
12302
12350
  }
12303
12351
  /**
12304
12352
  * Comparator that compares document keys according to the primary key sorting
12305
- * used by the `DbRemoteDocumentDocument` store (by collection path and then
12306
- * document ID).
12353
+ * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id
12354
+ * and then document ID).
12355
+ *
12356
+ * Visible for testing.
12307
12357
  */
12308
12358
  function dbKeyComparator(l, r) {
12309
- const cmp = l.path.length - r.path.length;
12310
- return cmp !== 0 ? cmp : DocumentKey.comparator(l, r);
12359
+ const left = l.path.toArray();
12360
+ const right = r.path.toArray();
12361
+ // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74
12362
+ let cmp = 0;
12363
+ for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) {
12364
+ cmp = primitiveComparator(left[i], right[i]);
12365
+ if (cmp) {
12366
+ return cmp;
12367
+ }
12368
+ }
12369
+ cmp = primitiveComparator(left.length, right.length);
12370
+ if (cmp) {
12371
+ return cmp;
12372
+ }
12373
+ cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]);
12374
+ if (cmp) {
12375
+ return cmp;
12376
+ }
12377
+ return primitiveComparator(left[left.length - 1], right[right.length - 1]);
12311
12378
  }
12312
12379
  /**
12313
12380
  * Schema Version for the Web client: