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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/firestore/lite/index.d.ts +1 -1
  2. package/dist/firestore/src/api/filter.d.ts +1 -1
  3. package/dist/firestore/src/api.d.ts +1 -1
  4. package/dist/firestore/src/core/bound.d.ts +49 -0
  5. package/dist/firestore/src/core/filter.d.ts +134 -0
  6. package/dist/firestore/src/core/order_by.d.ts +35 -0
  7. package/dist/firestore/src/core/query.d.ts +5 -6
  8. package/dist/firestore/src/core/target.d.ts +4 -120
  9. package/dist/firestore/src/lite-api/query.d.ts +273 -66
  10. package/dist/firestore/src/local/indexeddb_index_manager.d.ts +2 -0
  11. package/dist/firestore/src/protos/firestore_proto_api.d.ts +1 -1
  12. package/dist/firestore/src/remote/serializer.d.ts +10 -3
  13. package/dist/firestore/src/util/logic_utils.d.ts +52 -0
  14. package/dist/firestore/test/unit/core/filter.test.d.ts +17 -0
  15. package/dist/firestore/test/unit/util/logic_utils.test.d.ts +17 -0
  16. package/dist/firestore/test/util/helpers.d.ts +5 -1
  17. package/dist/index.d.ts +138 -62
  18. package/dist/index.esm2017.js +4046 -3512
  19. package/dist/index.esm2017.js.map +1 -1
  20. package/dist/index.esm5.js +4366 -3816
  21. package/dist/index.esm5.js.map +1 -1
  22. package/dist/index.node.cjs.js +1291 -555
  23. package/dist/index.node.cjs.js.map +1 -1
  24. package/dist/index.node.mjs +1284 -556
  25. package/dist/index.node.mjs.map +1 -1
  26. package/dist/index.rn.js +4145 -3611
  27. package/dist/index.rn.js.map +1 -1
  28. package/dist/internal.d.ts +320 -65
  29. package/dist/lite/firestore/lite/index.d.ts +1 -1
  30. package/dist/lite/firestore/src/api/filter.d.ts +1 -1
  31. package/dist/lite/firestore/src/api.d.ts +1 -1
  32. package/dist/lite/firestore/src/core/bound.d.ts +49 -0
  33. package/dist/lite/firestore/src/core/filter.d.ts +134 -0
  34. package/dist/lite/firestore/src/core/order_by.d.ts +35 -0
  35. package/dist/lite/firestore/src/core/query.d.ts +5 -6
  36. package/dist/lite/firestore/src/core/target.d.ts +4 -120
  37. package/dist/lite/firestore/src/lite-api/query.d.ts +273 -66
  38. package/dist/lite/firestore/src/local/indexeddb_index_manager.d.ts +2 -0
  39. package/dist/lite/firestore/src/protos/firestore_proto_api.d.ts +1 -1
  40. package/dist/lite/firestore/src/remote/serializer.d.ts +10 -3
  41. package/dist/lite/firestore/src/util/logic_utils.d.ts +52 -0
  42. package/dist/lite/firestore/test/unit/core/filter.test.d.ts +17 -0
  43. package/dist/lite/firestore/test/unit/util/logic_utils.test.d.ts +17 -0
  44. package/dist/lite/firestore/test/util/helpers.d.ts +5 -1
  45. package/dist/lite/index.browser.esm2017.js +2119 -1843
  46. package/dist/lite/index.browser.esm2017.js.map +1 -1
  47. package/dist/lite/index.browser.esm5.js +1957 -1737
  48. package/dist/lite/index.browser.esm5.js.map +1 -1
  49. package/dist/lite/index.d.ts +138 -62
  50. package/dist/lite/index.node.cjs.js +2093 -1717
  51. package/dist/lite/index.node.cjs.js.map +1 -1
  52. package/dist/lite/index.node.mjs +2086 -1718
  53. package/dist/lite/index.node.mjs.map +1 -1
  54. package/dist/lite/index.rn.esm2017.js +2118 -1841
  55. package/dist/lite/index.rn.esm2017.js.map +1 -1
  56. package/dist/lite/internal.d.ts +320 -65
  57. package/dist/lite/packages/firestore/dist/lite/index.browser.esm2017.d.ts +320 -175
  58. package/dist/lite/packages/firestore/lite/index.d.ts +1 -1
  59. package/dist/lite/packages/firestore/src/api/filter.d.ts +1 -1
  60. package/dist/lite/packages/firestore/src/api.d.ts +1 -1
  61. package/dist/lite/packages/firestore/src/core/bound.d.ts +49 -0
  62. package/dist/lite/packages/firestore/src/core/filter.d.ts +134 -0
  63. package/dist/lite/packages/firestore/src/core/order_by.d.ts +35 -0
  64. package/dist/lite/packages/firestore/src/core/query.d.ts +5 -6
  65. package/dist/lite/packages/firestore/src/core/target.d.ts +4 -120
  66. package/dist/lite/packages/firestore/src/lite-api/query.d.ts +273 -66
  67. package/dist/lite/packages/firestore/src/local/indexeddb_index_manager.d.ts +2 -0
  68. package/dist/lite/packages/firestore/src/protos/firestore_proto_api.d.ts +1 -1
  69. package/dist/lite/packages/firestore/src/remote/serializer.d.ts +10 -3
  70. package/dist/lite/packages/firestore/src/util/logic_utils.d.ts +52 -0
  71. package/dist/lite/packages/firestore/test/unit/core/filter.test.d.ts +17 -0
  72. package/dist/lite/packages/firestore/test/unit/util/logic_utils.test.d.ts +17 -0
  73. package/dist/lite/packages/firestore/test/util/helpers.d.ts +5 -1
  74. package/dist/lite/private.d.ts +232 -65
  75. package/dist/packages/firestore/dist/index.esm2017.d.ts +333 -209
  76. package/dist/packages/firestore/lite/index.d.ts +1 -1
  77. package/dist/packages/firestore/src/api/filter.d.ts +1 -1
  78. package/dist/packages/firestore/src/api.d.ts +1 -1
  79. package/dist/packages/firestore/src/core/bound.d.ts +49 -0
  80. package/dist/packages/firestore/src/core/filter.d.ts +134 -0
  81. package/dist/packages/firestore/src/core/order_by.d.ts +35 -0
  82. package/dist/packages/firestore/src/core/query.d.ts +5 -6
  83. package/dist/packages/firestore/src/core/target.d.ts +4 -120
  84. package/dist/packages/firestore/src/lite-api/query.d.ts +273 -66
  85. package/dist/packages/firestore/src/local/indexeddb_index_manager.d.ts +2 -0
  86. package/dist/packages/firestore/src/protos/firestore_proto_api.d.ts +1 -1
  87. package/dist/packages/firestore/src/remote/serializer.d.ts +10 -3
  88. package/dist/packages/firestore/src/util/logic_utils.d.ts +52 -0
  89. package/dist/packages/firestore/test/unit/core/filter.test.d.ts +17 -0
  90. package/dist/packages/firestore/test/unit/util/logic_utils.test.d.ts +17 -0
  91. package/dist/packages/firestore/test/util/helpers.d.ts +5 -1
  92. package/dist/private.d.ts +232 -65
  93. package/package.json +11 -9
@@ -33,7 +33,7 @@ var grpc__namespace = /*#__PURE__*/_interopNamespace(grpc);
33
33
  var protoLoader__namespace = /*#__PURE__*/_interopNamespace(protoLoader);
34
34
 
35
35
  const name = "@firebase/firestore";
36
- const version$1 = "3.7.3-canary.ab3f16cba";
36
+ const version$1 = "3.7.3-canary.fde5adf63";
37
37
 
38
38
  /**
39
39
  * @license
@@ -86,7 +86,7 @@ User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');
86
86
  User.FIRST_PARTY = new User('first-party-uid');
87
87
  User.MOCK_USER = new User('mock-user');
88
88
 
89
- const version = "9.14.0-canary.ab3f16cba";
89
+ const version = "9.14.0-canary.fde5adf63";
90
90
 
91
91
  /**
92
92
  * @license
@@ -5303,7 +5303,7 @@ function compareDocumentsByField(field, d1, d2) {
5303
5303
 
5304
5304
  /**
5305
5305
  * @license
5306
- * Copyright 2019 Google LLC
5306
+ * Copyright 2022 Google LLC
5307
5307
  *
5308
5308
  * Licensed under the Apache License, Version 2.0 (the "License");
5309
5309
  * you may not use this file except in compliance with the License.
@@ -5317,391 +5317,136 @@ function compareDocumentsByField(field, d1, d2) {
5317
5317
  * See the License for the specific language governing permissions and
5318
5318
  * limitations under the License.
5319
5319
  */
5320
- // Visible for testing
5321
- class TargetImpl {
5322
- constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
5323
- this.path = path;
5324
- this.collectionGroup = collectionGroup;
5325
- this.orderBy = orderBy;
5326
- this.filters = filters;
5327
- this.limit = limit;
5328
- this.startAt = startAt;
5329
- this.endAt = endAt;
5330
- this.memoizedCanonicalId = null;
5331
- }
5332
- }
5333
5320
  /**
5334
- * Initializes a Target with a path and optional additional query constraints.
5335
- * Path must currently be empty if this is a collection group query.
5321
+ * Represents a bound of a query.
5336
5322
  *
5337
- * NOTE: you should always construct `Target` from `Query.toTarget` instead of
5338
- * using this factory method, because `Query` provides an implicit `orderBy`
5339
- * property.
5323
+ * The bound is specified with the given components representing a position and
5324
+ * whether it's just before or just after the position (relative to whatever the
5325
+ * query order is).
5326
+ *
5327
+ * The position represents a logical index position for a query. It's a prefix
5328
+ * of values for the (potentially implicit) order by clauses of a query.
5329
+ *
5330
+ * Bound provides a function to determine whether a document comes before or
5331
+ * after a bound. This is influenced by whether the position is just before or
5332
+ * just after the provided values.
5340
5333
  */
5341
- function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
5342
- return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt);
5334
+ class Bound {
5335
+ constructor(position, inclusive) {
5336
+ this.position = position;
5337
+ this.inclusive = inclusive;
5338
+ }
5343
5339
  }
5344
- function canonifyTarget(target) {
5345
- const targetImpl = debugCast(target);
5346
- if (targetImpl.memoizedCanonicalId === null) {
5347
- let str = targetImpl.path.canonicalString();
5348
- if (targetImpl.collectionGroup !== null) {
5349
- str += '|cg:' + targetImpl.collectionGroup;
5340
+ function boundCompareToDocument(bound, orderBy, doc) {
5341
+ let comparison = 0;
5342
+ for (let i = 0; i < bound.position.length; i++) {
5343
+ const orderByComponent = orderBy[i];
5344
+ const component = bound.position[i];
5345
+ if (orderByComponent.field.isKeyField()) {
5346
+ comparison = DocumentKey.comparator(DocumentKey.fromName(component.referenceValue), doc.key);
5350
5347
  }
5351
- str += '|f:';
5352
- str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');
5353
- str += '|ob:';
5354
- str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');
5355
- if (!isNullOrUndefined(targetImpl.limit)) {
5356
- str += '|l:';
5357
- str += targetImpl.limit;
5348
+ else {
5349
+ const docValue = doc.data.field(orderByComponent.field);
5350
+ comparison = valueCompare(component, docValue);
5358
5351
  }
5359
- if (targetImpl.startAt) {
5360
- str += '|lb:';
5361
- str += targetImpl.startAt.inclusive ? 'b:' : 'a:';
5362
- str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');
5352
+ if (orderByComponent.dir === "desc" /* Direction.DESCENDING */) {
5353
+ comparison = comparison * -1;
5363
5354
  }
5364
- if (targetImpl.endAt) {
5365
- str += '|ub:';
5366
- str += targetImpl.endAt.inclusive ? 'a:' : 'b:';
5367
- str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');
5355
+ if (comparison !== 0) {
5356
+ break;
5368
5357
  }
5369
- targetImpl.memoizedCanonicalId = str;
5370
5358
  }
5371
- return targetImpl.memoizedCanonicalId;
5359
+ return comparison;
5372
5360
  }
5373
- function stringifyTarget(target) {
5374
- let str = target.path.canonicalString();
5375
- if (target.collectionGroup !== null) {
5376
- str += ' collectionGroup=' + target.collectionGroup;
5377
- }
5378
- if (target.filters.length > 0) {
5379
- str += `, filters: [${target.filters
5380
- .map(f => stringifyFilter(f))
5381
- .join(', ')}]`;
5382
- }
5383
- if (!isNullOrUndefined(target.limit)) {
5384
- str += ', limit: ' + target.limit;
5385
- }
5386
- if (target.orderBy.length > 0) {
5387
- str += `, orderBy: [${target.orderBy
5388
- .map(o => stringifyOrderBy(o))
5389
- .join(', ')}]`;
5390
- }
5391
- if (target.startAt) {
5392
- str += ', startAt: ';
5393
- str += target.startAt.inclusive ? 'b:' : 'a:';
5394
- str += target.startAt.position.map(p => canonicalId(p)).join(',');
5395
- }
5396
- if (target.endAt) {
5397
- str += ', endAt: ';
5398
- str += target.endAt.inclusive ? 'a:' : 'b:';
5399
- str += target.endAt.position.map(p => canonicalId(p)).join(',');
5400
- }
5401
- return `Target(${str})`;
5361
+ /**
5362
+ * Returns true if a document sorts after a bound using the provided sort
5363
+ * order.
5364
+ */
5365
+ function boundSortsAfterDocument(bound, orderBy, doc) {
5366
+ const comparison = boundCompareToDocument(bound, orderBy, doc);
5367
+ return bound.inclusive ? comparison >= 0 : comparison > 0;
5402
5368
  }
5403
- function targetEquals(left, right) {
5404
- if (left.limit !== right.limit) {
5405
- return false;
5369
+ /**
5370
+ * Returns true if a document sorts before a bound using the provided sort
5371
+ * order.
5372
+ */
5373
+ function boundSortsBeforeDocument(bound, orderBy, doc) {
5374
+ const comparison = boundCompareToDocument(bound, orderBy, doc);
5375
+ return bound.inclusive ? comparison <= 0 : comparison < 0;
5376
+ }
5377
+ function boundEquals(left, right) {
5378
+ if (left === null) {
5379
+ return right === null;
5406
5380
  }
5407
- if (left.orderBy.length !== right.orderBy.length) {
5381
+ else if (right === null) {
5408
5382
  return false;
5409
5383
  }
5410
- for (let i = 0; i < left.orderBy.length; i++) {
5411
- if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {
5412
- return false;
5413
- }
5414
- }
5415
- if (left.filters.length !== right.filters.length) {
5384
+ if (left.inclusive !== right.inclusive ||
5385
+ left.position.length !== right.position.length) {
5416
5386
  return false;
5417
5387
  }
5418
- for (let i = 0; i < left.filters.length; i++) {
5419
- if (!filterEquals(left.filters[i], right.filters[i])) {
5388
+ for (let i = 0; i < left.position.length; i++) {
5389
+ const leftPosition = left.position[i];
5390
+ const rightPosition = right.position[i];
5391
+ if (!valueEquals(leftPosition, rightPosition)) {
5420
5392
  return false;
5421
5393
  }
5422
5394
  }
5423
- if (left.collectionGroup !== right.collectionGroup) {
5424
- return false;
5425
- }
5426
- if (!left.path.isEqual(right.path)) {
5427
- return false;
5428
- }
5429
- if (!boundEquals(left.startAt, right.startAt)) {
5430
- return false;
5431
- }
5432
- return boundEquals(left.endAt, right.endAt);
5433
- }
5434
- function targetIsDocumentTarget(target) {
5435
- return (DocumentKey.isDocumentKey(target.path) &&
5436
- target.collectionGroup === null &&
5437
- target.filters.length === 0);
5438
- }
5439
- /** Returns the field filters that target the given field path. */
5440
- function targetGetFieldFiltersForPath(target, path) {
5441
- return target.filters.filter(f => f instanceof FieldFilter && f.field.isEqual(path));
5442
- }
5395
+ return true;
5396
+ }
5397
+
5443
5398
  /**
5444
- * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
5445
- * filters. Returns `null` if there are no such filters.
5399
+ * @license
5400
+ * Copyright 2022 Google LLC
5401
+ *
5402
+ * Licensed under the Apache License, Version 2.0 (the "License");
5403
+ * you may not use this file except in compliance with the License.
5404
+ * You may obtain a copy of the License at
5405
+ *
5406
+ * http://www.apache.org/licenses/LICENSE-2.0
5407
+ *
5408
+ * Unless required by applicable law or agreed to in writing, software
5409
+ * distributed under the License is distributed on an "AS IS" BASIS,
5410
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5411
+ * See the License for the specific language governing permissions and
5412
+ * limitations under the License.
5446
5413
  */
5447
- function targetGetArrayValues(target, fieldIndex) {
5448
- const segment = fieldIndexGetArraySegment(fieldIndex);
5449
- if (segment === undefined) {
5450
- return null;
5451
- }
5452
- for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
5453
- switch (fieldFilter.op) {
5454
- case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */:
5455
- return fieldFilter.value.arrayValue.values || [];
5456
- case "array-contains" /* Operator.ARRAY_CONTAINS */:
5457
- return [fieldFilter.value];
5458
- // Remaining filters are not array filters.
5459
- }
5460
- }
5461
- return null;
5414
+ class Filter {
5462
5415
  }
5463
- /**
5464
- * Returns the list of values that are used in != or NOT_IN filters. Returns
5465
- * `null` if there are no such filters.
5466
- */
5467
- function targetGetNotInValues(target, fieldIndex) {
5468
- const values = new Map();
5469
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5470
- for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
5471
- switch (fieldFilter.op) {
5472
- case "==" /* Operator.EQUAL */:
5473
- case "in" /* Operator.IN */:
5474
- // Encode equality prefix, which is encoded in the index value before
5475
- // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
5476
- // `value != 'ab'`).
5477
- values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
5478
- break;
5479
- case "not-in" /* Operator.NOT_IN */:
5480
- case "!=" /* Operator.NOT_EQUAL */:
5481
- // NotIn/NotEqual is always a suffix. There cannot be any remaining
5482
- // segments and hence we can return early here.
5483
- values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
5484
- return Array.from(values.values());
5485
- // Remaining filters cannot be used as notIn bounds.
5416
+ class FieldFilter extends Filter {
5417
+ constructor(field, op, value) {
5418
+ super();
5419
+ this.field = field;
5420
+ this.op = op;
5421
+ this.value = value;
5422
+ }
5423
+ /**
5424
+ * Creates a filter based on the provided arguments.
5425
+ */
5426
+ static create(field, op, value) {
5427
+ if (field.isKeyField()) {
5428
+ if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) {
5429
+ return this.createKeyFieldInFilter(field, op, value);
5430
+ }
5431
+ else {
5432
+ return new KeyFieldFilter(field, op, value);
5486
5433
  }
5487
5434
  }
5488
- }
5489
- return null;
5490
- }
5491
- /**
5492
- * Returns a lower bound of field values that can be used as a starting point to
5493
- * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound
5494
- * exists.
5495
- */
5496
- function targetGetLowerBound(target, fieldIndex) {
5497
- const values = [];
5498
- let inclusive = true;
5499
- // For each segment, retrieve a lower bound if there is a suitable filter or
5500
- // startAt.
5501
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5502
- const segmentBound = segment.kind === 0 /* IndexKind.ASCENDING */
5503
- ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)
5504
- : targetGetDescendingBound(target, segment.fieldPath, target.startAt);
5505
- values.push(segmentBound.value);
5506
- inclusive && (inclusive = segmentBound.inclusive);
5507
- }
5508
- return new Bound(values, inclusive);
5509
- }
5510
- /**
5511
- * Returns an upper bound of field values that can be used as an ending point
5512
- * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no
5513
- * upper bound exists.
5514
- */
5515
- function targetGetUpperBound(target, fieldIndex) {
5516
- const values = [];
5517
- let inclusive = true;
5518
- // For each segment, retrieve an upper bound if there is a suitable filter or
5519
- // endAt.
5520
- for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5521
- const segmentBound = segment.kind === 0 /* IndexKind.ASCENDING */
5522
- ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)
5523
- : targetGetAscendingBound(target, segment.fieldPath, target.endAt);
5524
- values.push(segmentBound.value);
5525
- inclusive && (inclusive = segmentBound.inclusive);
5526
- }
5527
- return new Bound(values, inclusive);
5528
- }
5529
- /**
5530
- * Returns the value to use as the lower bound for ascending index segment at
5531
- * the provided `fieldPath` (or the upper bound for an descending segment).
5532
- */
5533
- function targetGetAscendingBound(target, fieldPath, bound) {
5534
- let value = MIN_VALUE;
5535
- let inclusive = true;
5536
- // Process all filters to find a value for the current field segment
5537
- for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
5538
- let filterValue = MIN_VALUE;
5539
- let filterInclusive = true;
5540
- switch (fieldFilter.op) {
5541
- case "<" /* Operator.LESS_THAN */:
5542
- case "<=" /* Operator.LESS_THAN_OR_EQUAL */:
5543
- filterValue = valuesGetLowerBound(fieldFilter.value);
5544
- break;
5545
- case "==" /* Operator.EQUAL */:
5546
- case "in" /* Operator.IN */:
5547
- case ">=" /* Operator.GREATER_THAN_OR_EQUAL */:
5548
- filterValue = fieldFilter.value;
5549
- break;
5550
- case ">" /* Operator.GREATER_THAN */:
5551
- filterValue = fieldFilter.value;
5552
- filterInclusive = false;
5553
- break;
5554
- case "!=" /* Operator.NOT_EQUAL */:
5555
- case "not-in" /* Operator.NOT_IN */:
5556
- filterValue = MIN_VALUE;
5557
- break;
5558
- // Remaining filters cannot be used as lower bounds.
5559
- }
5560
- if (lowerBoundCompare({ value, inclusive }, { value: filterValue, inclusive: filterInclusive }) < 0) {
5561
- value = filterValue;
5562
- inclusive = filterInclusive;
5563
- }
5564
- }
5565
- // If there is an additional bound, compare the values against the existing
5566
- // range to see if we can narrow the scope.
5567
- if (bound !== null) {
5568
- for (let i = 0; i < target.orderBy.length; ++i) {
5569
- const orderBy = target.orderBy[i];
5570
- if (orderBy.field.isEqual(fieldPath)) {
5571
- const cursorValue = bound.position[i];
5572
- if (lowerBoundCompare({ value, inclusive }, { value: cursorValue, inclusive: bound.inclusive }) < 0) {
5573
- value = cursorValue;
5574
- inclusive = bound.inclusive;
5575
- }
5576
- break;
5577
- }
5578
- }
5579
- }
5580
- return { value, inclusive };
5581
- }
5582
- /**
5583
- * Returns the value to use as the upper bound for ascending index segment at
5584
- * the provided `fieldPath` (or the lower bound for a descending segment).
5585
- */
5586
- function targetGetDescendingBound(target, fieldPath, bound) {
5587
- let value = MAX_VALUE;
5588
- let inclusive = true;
5589
- // Process all filters to find a value for the current field segment
5590
- for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
5591
- let filterValue = MAX_VALUE;
5592
- let filterInclusive = true;
5593
- switch (fieldFilter.op) {
5594
- case ">=" /* Operator.GREATER_THAN_OR_EQUAL */:
5595
- case ">" /* Operator.GREATER_THAN */:
5596
- filterValue = valuesGetUpperBound(fieldFilter.value);
5597
- filterInclusive = false;
5598
- break;
5599
- case "==" /* Operator.EQUAL */:
5600
- case "in" /* Operator.IN */:
5601
- case "<=" /* Operator.LESS_THAN_OR_EQUAL */:
5602
- filterValue = fieldFilter.value;
5603
- break;
5604
- case "<" /* Operator.LESS_THAN */:
5605
- filterValue = fieldFilter.value;
5606
- filterInclusive = false;
5607
- break;
5608
- case "!=" /* Operator.NOT_EQUAL */:
5609
- case "not-in" /* Operator.NOT_IN */:
5610
- filterValue = MAX_VALUE;
5611
- break;
5612
- // Remaining filters cannot be used as upper bounds.
5613
- }
5614
- if (upperBoundCompare({ value, inclusive }, { value: filterValue, inclusive: filterInclusive }) > 0) {
5615
- value = filterValue;
5616
- inclusive = filterInclusive;
5617
- }
5618
- }
5619
- // If there is an additional bound, compare the values against the existing
5620
- // range to see if we can narrow the scope.
5621
- if (bound !== null) {
5622
- for (let i = 0; i < target.orderBy.length; ++i) {
5623
- const orderBy = target.orderBy[i];
5624
- if (orderBy.field.isEqual(fieldPath)) {
5625
- const cursorValue = bound.position[i];
5626
- if (upperBoundCompare({ value, inclusive }, { value: cursorValue, inclusive: bound.inclusive }) > 0) {
5627
- value = cursorValue;
5628
- inclusive = bound.inclusive;
5629
- }
5630
- break;
5631
- }
5632
- }
5633
- }
5634
- return { value, inclusive };
5635
- }
5636
- /** Returns the number of segments of a perfect index for this target. */
5637
- function targetGetSegmentCount(target) {
5638
- let fields = new SortedSet(FieldPath$1.comparator);
5639
- let hasArraySegment = false;
5640
- for (const filter of target.filters) {
5641
- // TODO(orquery): Use the flattened filters here
5642
- const fieldFilter = filter;
5643
- // __name__ is not an explicit segment of any index, so we don't need to
5644
- // count it.
5645
- if (fieldFilter.field.isKeyField()) {
5646
- continue;
5647
- }
5648
- // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
5649
- // For instance, it is possible to have an index for "a ARRAY a ASC". Even
5650
- // though these are on the same field, they should be counted as two
5651
- // separate segments in an index.
5652
- if (fieldFilter.op === "array-contains" /* Operator.ARRAY_CONTAINS */ ||
5653
- fieldFilter.op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) {
5654
- hasArraySegment = true;
5655
- }
5656
- else {
5657
- fields = fields.add(fieldFilter.field);
5658
- }
5659
- }
5660
- for (const orderBy of target.orderBy) {
5661
- // __name__ is not an explicit segment of any index, so we don't need to
5662
- // count it.
5663
- if (!orderBy.field.isKeyField()) {
5664
- fields = fields.add(orderBy.field);
5665
- }
5666
- }
5667
- return fields.size + (hasArraySegment ? 1 : 0);
5668
- }
5669
- class Filter {
5670
- }
5671
- class FieldFilter extends Filter {
5672
- constructor(field, op, value) {
5673
- super();
5674
- this.field = field;
5675
- this.op = op;
5676
- this.value = value;
5677
- }
5678
- /**
5679
- * Creates a filter based on the provided arguments.
5680
- */
5681
- static create(field, op, value) {
5682
- if (field.isKeyField()) {
5683
- if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) {
5684
- return this.createKeyFieldInFilter(field, op, value);
5685
- }
5686
- else {
5687
- return new KeyFieldFilter(field, op, value);
5688
- }
5689
- }
5690
- else if (op === "array-contains" /* Operator.ARRAY_CONTAINS */) {
5691
- return new ArrayContainsFilter(field, value);
5692
- }
5693
- else if (op === "in" /* Operator.IN */) {
5694
- return new InFilter(field, value);
5695
- }
5696
- else if (op === "not-in" /* Operator.NOT_IN */) {
5697
- return new NotInFilter(field, value);
5698
- }
5699
- else if (op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) {
5700
- return new ArrayContainsAnyFilter(field, value);
5701
- }
5702
- else {
5703
- return new FieldFilter(field, op, value);
5704
- }
5435
+ else if (op === "array-contains" /* Operator.ARRAY_CONTAINS */) {
5436
+ return new ArrayContainsFilter(field, value);
5437
+ }
5438
+ else if (op === "in" /* Operator.IN */) {
5439
+ return new InFilter(field, value);
5440
+ }
5441
+ else if (op === "not-in" /* Operator.NOT_IN */) {
5442
+ return new NotInFilter(field, value);
5443
+ }
5444
+ else if (op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) {
5445
+ return new ArrayContainsAnyFilter(field, value);
5446
+ }
5447
+ else {
5448
+ return new FieldFilter(field, op, value);
5449
+ }
5705
5450
  }
5706
5451
  static createKeyFieldInFilter(field, op, value) {
5707
5452
  return op === "in" /* Operator.IN */
@@ -5748,53 +5493,199 @@ class FieldFilter extends Filter {
5748
5493
  "not-in" /* Operator.NOT_IN */
5749
5494
  ].indexOf(this.op) >= 0);
5750
5495
  }
5751
- }
5752
- function canonifyFilter(filter) {
5753
- // TODO(b/29183165): Technically, this won't be unique if two values have
5754
- // the same description, such as the int 3 and the string "3". So we should
5755
- // add the types in here somehow, too.
5756
- return (filter.field.canonicalString() +
5757
- filter.op.toString() +
5758
- canonicalId(filter.value));
5759
- }
5760
- function filterEquals(f1, f2) {
5761
- return (f1.op === f2.op &&
5762
- f1.field.isEqual(f2.field) &&
5763
- valueEquals(f1.value, f2.value));
5764
- }
5765
- /** Returns a debug description for `filter`. */
5766
- function stringifyFilter(filter) {
5767
- return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(filter.value)}`;
5768
- }
5769
- /** Filter that matches on key fields (i.e. '__name__'). */
5770
- class KeyFieldFilter extends FieldFilter {
5771
- constructor(field, op, value) {
5772
- super(field, op, value);
5773
- this.key = DocumentKey.fromName(value.referenceValue);
5496
+ getFlattenedFilters() {
5497
+ return [this];
5774
5498
  }
5775
- matches(doc) {
5776
- const comparison = DocumentKey.comparator(doc.key, this.key);
5777
- return this.matchesComparison(comparison);
5499
+ getFilters() {
5500
+ return [this];
5501
+ }
5502
+ getFirstInequalityField() {
5503
+ if (this.isInequality()) {
5504
+ return this.field;
5505
+ }
5506
+ return null;
5778
5507
  }
5779
5508
  }
5780
- /** Filter that matches on key fields within an array. */
5781
- class KeyFieldInFilter extends FieldFilter {
5782
- constructor(field, value) {
5783
- super(field, "in" /* Operator.IN */, value);
5784
- this.keys = extractDocumentKeysFromArrayValue("in" /* Operator.IN */, value);
5509
+ class CompositeFilter extends Filter {
5510
+ constructor(filters, op) {
5511
+ super();
5512
+ this.filters = filters;
5513
+ this.op = op;
5514
+ this.memoizedFlattenedFilters = null;
5515
+ }
5516
+ /**
5517
+ * Creates a filter based on the provided arguments.
5518
+ */
5519
+ static create(filters, op) {
5520
+ return new CompositeFilter(filters, op);
5785
5521
  }
5786
5522
  matches(doc) {
5787
- return this.keys.some(key => key.isEqual(doc.key));
5523
+ if (compositeFilterIsConjunction(this)) {
5524
+ // For conjunctions, all filters must match, so return false if any filter doesn't match.
5525
+ return this.filters.find(filter => !filter.matches(doc)) === undefined;
5526
+ }
5527
+ else {
5528
+ // For disjunctions, at least one filter should match.
5529
+ return this.filters.find(filter => filter.matches(doc)) !== undefined;
5530
+ }
5788
5531
  }
5789
- }
5790
- /** Filter that matches on key fields not present within an array. */
5791
- class KeyFieldNotInFilter extends FieldFilter {
5792
- constructor(field, value) {
5793
- super(field, "not-in" /* Operator.NOT_IN */, value);
5794
- this.keys = extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */, value);
5532
+ getFlattenedFilters() {
5533
+ if (this.memoizedFlattenedFilters !== null) {
5534
+ return this.memoizedFlattenedFilters;
5535
+ }
5536
+ this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => {
5537
+ return result.concat(subfilter.getFlattenedFilters());
5538
+ }, []);
5539
+ return this.memoizedFlattenedFilters;
5795
5540
  }
5796
- matches(doc) {
5797
- return !this.keys.some(key => key.isEqual(doc.key));
5541
+ // Returns a mutable copy of `this.filters`
5542
+ getFilters() {
5543
+ return Object.assign([], this.filters);
5544
+ }
5545
+ getFirstInequalityField() {
5546
+ const found = this.findFirstMatchingFilter(filter => filter.isInequality());
5547
+ if (found !== null) {
5548
+ return found.field;
5549
+ }
5550
+ return null;
5551
+ }
5552
+ // Performs a depth-first search to find and return the first FieldFilter in the composite filter
5553
+ // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the
5554
+ // predicate.
5555
+ findFirstMatchingFilter(predicate) {
5556
+ for (const fieldFilter of this.getFlattenedFilters()) {
5557
+ if (predicate(fieldFilter)) {
5558
+ return fieldFilter;
5559
+ }
5560
+ }
5561
+ return null;
5562
+ }
5563
+ }
5564
+ function compositeFilterIsConjunction(compositeFilter) {
5565
+ return compositeFilter.op === "and" /* CompositeOperator.AND */;
5566
+ }
5567
+ function compositeFilterIsDisjunction(compositeFilter) {
5568
+ return compositeFilter.op === "or" /* CompositeOperator.OR */;
5569
+ }
5570
+ /**
5571
+ * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.
5572
+ */
5573
+ function compositeFilterIsFlatConjunction(compositeFilter) {
5574
+ return (compositeFilterIsFlat(compositeFilter) &&
5575
+ compositeFilterIsConjunction(compositeFilter));
5576
+ }
5577
+ /**
5578
+ * Returns true if this filter does not contain any composite filters. Returns false otherwise.
5579
+ */
5580
+ function compositeFilterIsFlat(compositeFilter) {
5581
+ for (const filter of compositeFilter.filters) {
5582
+ if (filter instanceof CompositeFilter) {
5583
+ return false;
5584
+ }
5585
+ }
5586
+ return true;
5587
+ }
5588
+ function canonifyFilter(filter) {
5589
+ if (filter instanceof FieldFilter) {
5590
+ // TODO(b/29183165): Technically, this won't be unique if two values have
5591
+ // the same description, such as the int 3 and the string "3". So we should
5592
+ // add the types in here somehow, too.
5593
+ return (filter.field.canonicalString() +
5594
+ filter.op.toString() +
5595
+ canonicalId(filter.value));
5596
+ }
5597
+ else {
5598
+ // filter instanceof CompositeFilter
5599
+ const canonicalIdsString = filter.filters
5600
+ .map(filter => canonifyFilter(filter))
5601
+ .join(',');
5602
+ return `${filter.op}(${canonicalIdsString})`;
5603
+ }
5604
+ }
5605
+ function filterEquals(f1, f2) {
5606
+ if (f1 instanceof FieldFilter) {
5607
+ return fieldFilterEquals(f1, f2);
5608
+ }
5609
+ else if (f1 instanceof CompositeFilter) {
5610
+ return compositeFilterEquals(f1, f2);
5611
+ }
5612
+ else {
5613
+ fail();
5614
+ }
5615
+ }
5616
+ function fieldFilterEquals(f1, f2) {
5617
+ return (f2 instanceof FieldFilter &&
5618
+ f1.op === f2.op &&
5619
+ f1.field.isEqual(f2.field) &&
5620
+ valueEquals(f1.value, f2.value));
5621
+ }
5622
+ function compositeFilterEquals(f1, f2) {
5623
+ if (f2 instanceof CompositeFilter &&
5624
+ f1.op === f2.op &&
5625
+ f1.filters.length === f2.filters.length) {
5626
+ const subFiltersMatch = f1.filters.reduce((result, f1Filter, index) => result && filterEquals(f1Filter, f2.filters[index]), true);
5627
+ return subFiltersMatch;
5628
+ }
5629
+ return false;
5630
+ }
5631
+ /**
5632
+ * Returns a new composite filter that contains all filter from
5633
+ * `compositeFilter` plus all the given filters in `otherFilters`.
5634
+ */
5635
+ function compositeFilterWithAddedFilters(compositeFilter, otherFilters) {
5636
+ const mergedFilters = compositeFilter.filters.concat(otherFilters);
5637
+ return CompositeFilter.create(mergedFilters, compositeFilter.op);
5638
+ }
5639
+ /** Returns a debug description for `filter`. */
5640
+ function stringifyFilter(filter) {
5641
+ if (filter instanceof FieldFilter) {
5642
+ return stringifyFieldFilter(filter);
5643
+ }
5644
+ else if (filter instanceof CompositeFilter) {
5645
+ return stringifyCompositeFilter(filter);
5646
+ }
5647
+ else {
5648
+ return 'Filter';
5649
+ }
5650
+ }
5651
+ function stringifyCompositeFilter(filter) {
5652
+ return (filter.op.toString() +
5653
+ ` {` +
5654
+ filter.getFilters().map(stringifyFilter).join(' ,') +
5655
+ '}');
5656
+ }
5657
+ function stringifyFieldFilter(filter) {
5658
+ return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(filter.value)}`;
5659
+ }
5660
+ /** Filter that matches on key fields (i.e. '__name__'). */
5661
+ class KeyFieldFilter extends FieldFilter {
5662
+ constructor(field, op, value) {
5663
+ super(field, op, value);
5664
+ this.key = DocumentKey.fromName(value.referenceValue);
5665
+ }
5666
+ matches(doc) {
5667
+ const comparison = DocumentKey.comparator(doc.key, this.key);
5668
+ return this.matchesComparison(comparison);
5669
+ }
5670
+ }
5671
+ /** Filter that matches on key fields within an array. */
5672
+ class KeyFieldInFilter extends FieldFilter {
5673
+ constructor(field, value) {
5674
+ super(field, "in" /* Operator.IN */, value);
5675
+ this.keys = extractDocumentKeysFromArrayValue("in" /* Operator.IN */, value);
5676
+ }
5677
+ matches(doc) {
5678
+ return this.keys.some(key => key.isEqual(doc.key));
5679
+ }
5680
+ }
5681
+ /** Filter that matches on key fields not present within an array. */
5682
+ class KeyFieldNotInFilter extends FieldFilter {
5683
+ constructor(field, value) {
5684
+ super(field, "not-in" /* Operator.NOT_IN */, value);
5685
+ this.keys = extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */, value);
5686
+ }
5687
+ matches(doc) {
5688
+ return !this.keys.some(key => key.isEqual(doc.key));
5798
5689
  }
5799
5690
  }
5800
5691
  function extractDocumentKeysFromArrayValue(op, value) {
@@ -5848,27 +5739,24 @@ class ArrayContainsAnyFilter extends FieldFilter {
5848
5739
  }
5849
5740
  return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val));
5850
5741
  }
5851
- }
5742
+ }
5743
+
5852
5744
  /**
5853
- * Represents a bound of a query.
5745
+ * @license
5746
+ * Copyright 2022 Google LLC
5854
5747
  *
5855
- * The bound is specified with the given components representing a position and
5856
- * whether it's just before or just after the position (relative to whatever the
5857
- * query order is).
5748
+ * Licensed under the Apache License, Version 2.0 (the "License");
5749
+ * you may not use this file except in compliance with the License.
5750
+ * You may obtain a copy of the License at
5858
5751
  *
5859
- * The position represents a logical index position for a query. It's a prefix
5860
- * of values for the (potentially implicit) order by clauses of a query.
5752
+ * http://www.apache.org/licenses/LICENSE-2.0
5861
5753
  *
5862
- * Bound provides a function to determine whether a document comes before or
5863
- * after a bound. This is influenced by whether the position is just before or
5864
- * just after the provided values.
5754
+ * Unless required by applicable law or agreed to in writing, software
5755
+ * distributed under the License is distributed on an "AS IS" BASIS,
5756
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5757
+ * See the License for the specific language governing permissions and
5758
+ * limitations under the License.
5865
5759
  */
5866
- class Bound {
5867
- constructor(position, inclusive) {
5868
- this.position = position;
5869
- this.inclusive = inclusive;
5870
- }
5871
- }
5872
5760
  /**
5873
5761
  * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
5874
5762
  */
@@ -5887,63 +5775,375 @@ function stringifyOrderBy(orderBy) {
5887
5775
  }
5888
5776
  function orderByEquals(left, right) {
5889
5777
  return left.dir === right.dir && left.field.isEqual(right.field);
5778
+ }
5779
+
5780
+ /**
5781
+ * @license
5782
+ * Copyright 2019 Google LLC
5783
+ *
5784
+ * Licensed under the Apache License, Version 2.0 (the "License");
5785
+ * you may not use this file except in compliance with the License.
5786
+ * You may obtain a copy of the License at
5787
+ *
5788
+ * http://www.apache.org/licenses/LICENSE-2.0
5789
+ *
5790
+ * Unless required by applicable law or agreed to in writing, software
5791
+ * distributed under the License is distributed on an "AS IS" BASIS,
5792
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5793
+ * See the License for the specific language governing permissions and
5794
+ * limitations under the License.
5795
+ */
5796
+ // Visible for testing
5797
+ class TargetImpl {
5798
+ constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
5799
+ this.path = path;
5800
+ this.collectionGroup = collectionGroup;
5801
+ this.orderBy = orderBy;
5802
+ this.filters = filters;
5803
+ this.limit = limit;
5804
+ this.startAt = startAt;
5805
+ this.endAt = endAt;
5806
+ this.memoizedCanonicalId = null;
5807
+ }
5890
5808
  }
5891
- function boundCompareToDocument(bound, orderBy, doc) {
5892
- let comparison = 0;
5893
- for (let i = 0; i < bound.position.length; i++) {
5894
- const orderByComponent = orderBy[i];
5895
- const component = bound.position[i];
5896
- if (orderByComponent.field.isKeyField()) {
5897
- comparison = DocumentKey.comparator(DocumentKey.fromName(component.referenceValue), doc.key);
5809
+ /**
5810
+ * Initializes a Target with a path and optional additional query constraints.
5811
+ * Path must currently be empty if this is a collection group query.
5812
+ *
5813
+ * NOTE: you should always construct `Target` from `Query.toTarget` instead of
5814
+ * using this factory method, because `Query` provides an implicit `orderBy`
5815
+ * property.
5816
+ */
5817
+ function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) {
5818
+ return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt);
5819
+ }
5820
+ function canonifyTarget(target) {
5821
+ const targetImpl = debugCast(target);
5822
+ if (targetImpl.memoizedCanonicalId === null) {
5823
+ let str = targetImpl.path.canonicalString();
5824
+ if (targetImpl.collectionGroup !== null) {
5825
+ str += '|cg:' + targetImpl.collectionGroup;
5898
5826
  }
5899
- else {
5900
- const docValue = doc.data.field(orderByComponent.field);
5901
- comparison = valueCompare(component, docValue);
5827
+ str += '|f:';
5828
+ str += targetImpl.filters.map(f => canonifyFilter(f)).join(',');
5829
+ str += '|ob:';
5830
+ str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(',');
5831
+ if (!isNullOrUndefined(targetImpl.limit)) {
5832
+ str += '|l:';
5833
+ str += targetImpl.limit;
5902
5834
  }
5903
- if (orderByComponent.dir === "desc" /* Direction.DESCENDING */) {
5904
- comparison = comparison * -1;
5835
+ if (targetImpl.startAt) {
5836
+ str += '|lb:';
5837
+ str += targetImpl.startAt.inclusive ? 'b:' : 'a:';
5838
+ str += targetImpl.startAt.position.map(p => canonicalId(p)).join(',');
5905
5839
  }
5906
- if (comparison !== 0) {
5907
- break;
5840
+ if (targetImpl.endAt) {
5841
+ str += '|ub:';
5842
+ str += targetImpl.endAt.inclusive ? 'a:' : 'b:';
5843
+ str += targetImpl.endAt.position.map(p => canonicalId(p)).join(',');
5908
5844
  }
5845
+ targetImpl.memoizedCanonicalId = str;
5909
5846
  }
5910
- return comparison;
5847
+ return targetImpl.memoizedCanonicalId;
5848
+ }
5849
+ function stringifyTarget(target) {
5850
+ let str = target.path.canonicalString();
5851
+ if (target.collectionGroup !== null) {
5852
+ str += ' collectionGroup=' + target.collectionGroup;
5853
+ }
5854
+ if (target.filters.length > 0) {
5855
+ str += `, filters: [${target.filters
5856
+ .map(f => stringifyFilter(f))
5857
+ .join(', ')}]`;
5858
+ }
5859
+ if (!isNullOrUndefined(target.limit)) {
5860
+ str += ', limit: ' + target.limit;
5861
+ }
5862
+ if (target.orderBy.length > 0) {
5863
+ str += `, orderBy: [${target.orderBy
5864
+ .map(o => stringifyOrderBy(o))
5865
+ .join(', ')}]`;
5866
+ }
5867
+ if (target.startAt) {
5868
+ str += ', startAt: ';
5869
+ str += target.startAt.inclusive ? 'b:' : 'a:';
5870
+ str += target.startAt.position.map(p => canonicalId(p)).join(',');
5871
+ }
5872
+ if (target.endAt) {
5873
+ str += ', endAt: ';
5874
+ str += target.endAt.inclusive ? 'a:' : 'b:';
5875
+ str += target.endAt.position.map(p => canonicalId(p)).join(',');
5876
+ }
5877
+ return `Target(${str})`;
5878
+ }
5879
+ function targetEquals(left, right) {
5880
+ if (left.limit !== right.limit) {
5881
+ return false;
5882
+ }
5883
+ if (left.orderBy.length !== right.orderBy.length) {
5884
+ return false;
5885
+ }
5886
+ for (let i = 0; i < left.orderBy.length; i++) {
5887
+ if (!orderByEquals(left.orderBy[i], right.orderBy[i])) {
5888
+ return false;
5889
+ }
5890
+ }
5891
+ if (left.filters.length !== right.filters.length) {
5892
+ return false;
5893
+ }
5894
+ for (let i = 0; i < left.filters.length; i++) {
5895
+ if (!filterEquals(left.filters[i], right.filters[i])) {
5896
+ return false;
5897
+ }
5898
+ }
5899
+ if (left.collectionGroup !== right.collectionGroup) {
5900
+ return false;
5901
+ }
5902
+ if (!left.path.isEqual(right.path)) {
5903
+ return false;
5904
+ }
5905
+ if (!boundEquals(left.startAt, right.startAt)) {
5906
+ return false;
5907
+ }
5908
+ return boundEquals(left.endAt, right.endAt);
5909
+ }
5910
+ function targetIsDocumentTarget(target) {
5911
+ return (DocumentKey.isDocumentKey(target.path) &&
5912
+ target.collectionGroup === null &&
5913
+ target.filters.length === 0);
5914
+ }
5915
+ /** Returns the field filters that target the given field path. */
5916
+ function targetGetFieldFiltersForPath(target, path) {
5917
+ return target.filters.filter(f => f instanceof FieldFilter && f.field.isEqual(path));
5911
5918
  }
5912
5919
  /**
5913
- * Returns true if a document sorts after a bound using the provided sort
5914
- * order.
5920
+ * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
5921
+ * filters. Returns `null` if there are no such filters.
5915
5922
  */
5916
- function boundSortsAfterDocument(bound, orderBy, doc) {
5917
- const comparison = boundCompareToDocument(bound, orderBy, doc);
5918
- return bound.inclusive ? comparison >= 0 : comparison > 0;
5923
+ function targetGetArrayValues(target, fieldIndex) {
5924
+ const segment = fieldIndexGetArraySegment(fieldIndex);
5925
+ if (segment === undefined) {
5926
+ return null;
5927
+ }
5928
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
5929
+ switch (fieldFilter.op) {
5930
+ case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */:
5931
+ return fieldFilter.value.arrayValue.values || [];
5932
+ case "array-contains" /* Operator.ARRAY_CONTAINS */:
5933
+ return [fieldFilter.value];
5934
+ // Remaining filters are not array filters.
5935
+ }
5936
+ }
5937
+ return null;
5919
5938
  }
5920
5939
  /**
5921
- * Returns true if a document sorts before a bound using the provided sort
5922
- * order.
5940
+ * Returns the list of values that are used in != or NOT_IN filters. Returns
5941
+ * `null` if there are no such filters.
5923
5942
  */
5924
- function boundSortsBeforeDocument(bound, orderBy, doc) {
5925
- const comparison = boundCompareToDocument(bound, orderBy, doc);
5926
- return bound.inclusive ? comparison <= 0 : comparison < 0;
5943
+ function targetGetNotInValues(target, fieldIndex) {
5944
+ const values = new Map();
5945
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5946
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) {
5947
+ switch (fieldFilter.op) {
5948
+ case "==" /* Operator.EQUAL */:
5949
+ case "in" /* Operator.IN */:
5950
+ // Encode equality prefix, which is encoded in the index value before
5951
+ // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
5952
+ // `value != 'ab'`).
5953
+ values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
5954
+ break;
5955
+ case "not-in" /* Operator.NOT_IN */:
5956
+ case "!=" /* Operator.NOT_EQUAL */:
5957
+ // NotIn/NotEqual is always a suffix. There cannot be any remaining
5958
+ // segments and hence we can return early here.
5959
+ values.set(segment.fieldPath.canonicalString(), fieldFilter.value);
5960
+ return Array.from(values.values());
5961
+ // Remaining filters cannot be used as notIn bounds.
5962
+ }
5963
+ }
5964
+ }
5965
+ return null;
5927
5966
  }
5928
- function boundEquals(left, right) {
5929
- if (left === null) {
5930
- return right === null;
5967
+ /**
5968
+ * Returns a lower bound of field values that can be used as a starting point to
5969
+ * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound
5970
+ * exists.
5971
+ */
5972
+ function targetGetLowerBound(target, fieldIndex) {
5973
+ const values = [];
5974
+ let inclusive = true;
5975
+ // For each segment, retrieve a lower bound if there is a suitable filter or
5976
+ // startAt.
5977
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5978
+ const segmentBound = segment.kind === 0 /* IndexKind.ASCENDING */
5979
+ ? targetGetAscendingBound(target, segment.fieldPath, target.startAt)
5980
+ : targetGetDescendingBound(target, segment.fieldPath, target.startAt);
5981
+ values.push(segmentBound.value);
5982
+ inclusive && (inclusive = segmentBound.inclusive);
5983
+ }
5984
+ return new Bound(values, inclusive);
5985
+ }
5986
+ /**
5987
+ * Returns an upper bound of field values that can be used as an ending point
5988
+ * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no
5989
+ * upper bound exists.
5990
+ */
5991
+ function targetGetUpperBound(target, fieldIndex) {
5992
+ const values = [];
5993
+ let inclusive = true;
5994
+ // For each segment, retrieve an upper bound if there is a suitable filter or
5995
+ // endAt.
5996
+ for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
5997
+ const segmentBound = segment.kind === 0 /* IndexKind.ASCENDING */
5998
+ ? targetGetDescendingBound(target, segment.fieldPath, target.endAt)
5999
+ : targetGetAscendingBound(target, segment.fieldPath, target.endAt);
6000
+ values.push(segmentBound.value);
6001
+ inclusive && (inclusive = segmentBound.inclusive);
6002
+ }
6003
+ return new Bound(values, inclusive);
6004
+ }
6005
+ /**
6006
+ * Returns the value to use as the lower bound for ascending index segment at
6007
+ * the provided `fieldPath` (or the upper bound for an descending segment).
6008
+ */
6009
+ function targetGetAscendingBound(target, fieldPath, bound) {
6010
+ let value = MIN_VALUE;
6011
+ let inclusive = true;
6012
+ // Process all filters to find a value for the current field segment
6013
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
6014
+ let filterValue = MIN_VALUE;
6015
+ let filterInclusive = true;
6016
+ switch (fieldFilter.op) {
6017
+ case "<" /* Operator.LESS_THAN */:
6018
+ case "<=" /* Operator.LESS_THAN_OR_EQUAL */:
6019
+ filterValue = valuesGetLowerBound(fieldFilter.value);
6020
+ break;
6021
+ case "==" /* Operator.EQUAL */:
6022
+ case "in" /* Operator.IN */:
6023
+ case ">=" /* Operator.GREATER_THAN_OR_EQUAL */:
6024
+ filterValue = fieldFilter.value;
6025
+ break;
6026
+ case ">" /* Operator.GREATER_THAN */:
6027
+ filterValue = fieldFilter.value;
6028
+ filterInclusive = false;
6029
+ break;
6030
+ case "!=" /* Operator.NOT_EQUAL */:
6031
+ case "not-in" /* Operator.NOT_IN */:
6032
+ filterValue = MIN_VALUE;
6033
+ break;
6034
+ // Remaining filters cannot be used as lower bounds.
6035
+ }
6036
+ if (lowerBoundCompare({ value, inclusive }, { value: filterValue, inclusive: filterInclusive }) < 0) {
6037
+ value = filterValue;
6038
+ inclusive = filterInclusive;
6039
+ }
6040
+ }
6041
+ // If there is an additional bound, compare the values against the existing
6042
+ // range to see if we can narrow the scope.
6043
+ if (bound !== null) {
6044
+ for (let i = 0; i < target.orderBy.length; ++i) {
6045
+ const orderBy = target.orderBy[i];
6046
+ if (orderBy.field.isEqual(fieldPath)) {
6047
+ const cursorValue = bound.position[i];
6048
+ if (lowerBoundCompare({ value, inclusive }, { value: cursorValue, inclusive: bound.inclusive }) < 0) {
6049
+ value = cursorValue;
6050
+ inclusive = bound.inclusive;
6051
+ }
6052
+ break;
6053
+ }
6054
+ }
6055
+ }
6056
+ return { value, inclusive };
6057
+ }
6058
+ /**
6059
+ * Returns the value to use as the upper bound for ascending index segment at
6060
+ * the provided `fieldPath` (or the lower bound for a descending segment).
6061
+ */
6062
+ function targetGetDescendingBound(target, fieldPath, bound) {
6063
+ let value = MAX_VALUE;
6064
+ let inclusive = true;
6065
+ // Process all filters to find a value for the current field segment
6066
+ for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) {
6067
+ let filterValue = MAX_VALUE;
6068
+ let filterInclusive = true;
6069
+ switch (fieldFilter.op) {
6070
+ case ">=" /* Operator.GREATER_THAN_OR_EQUAL */:
6071
+ case ">" /* Operator.GREATER_THAN */:
6072
+ filterValue = valuesGetUpperBound(fieldFilter.value);
6073
+ filterInclusive = false;
6074
+ break;
6075
+ case "==" /* Operator.EQUAL */:
6076
+ case "in" /* Operator.IN */:
6077
+ case "<=" /* Operator.LESS_THAN_OR_EQUAL */:
6078
+ filterValue = fieldFilter.value;
6079
+ break;
6080
+ case "<" /* Operator.LESS_THAN */:
6081
+ filterValue = fieldFilter.value;
6082
+ filterInclusive = false;
6083
+ break;
6084
+ case "!=" /* Operator.NOT_EQUAL */:
6085
+ case "not-in" /* Operator.NOT_IN */:
6086
+ filterValue = MAX_VALUE;
6087
+ break;
6088
+ // Remaining filters cannot be used as upper bounds.
6089
+ }
6090
+ if (upperBoundCompare({ value, inclusive }, { value: filterValue, inclusive: filterInclusive }) > 0) {
6091
+ value = filterValue;
6092
+ inclusive = filterInclusive;
6093
+ }
5931
6094
  }
5932
- else if (right === null) {
5933
- return false;
6095
+ // If there is an additional bound, compare the values against the existing
6096
+ // range to see if we can narrow the scope.
6097
+ if (bound !== null) {
6098
+ for (let i = 0; i < target.orderBy.length; ++i) {
6099
+ const orderBy = target.orderBy[i];
6100
+ if (orderBy.field.isEqual(fieldPath)) {
6101
+ const cursorValue = bound.position[i];
6102
+ if (upperBoundCompare({ value, inclusive }, { value: cursorValue, inclusive: bound.inclusive }) > 0) {
6103
+ value = cursorValue;
6104
+ inclusive = bound.inclusive;
6105
+ }
6106
+ break;
6107
+ }
6108
+ }
5934
6109
  }
5935
- if (left.inclusive !== right.inclusive ||
5936
- left.position.length !== right.position.length) {
5937
- return false;
6110
+ return { value, inclusive };
6111
+ }
6112
+ /** Returns the number of segments of a perfect index for this target. */
6113
+ function targetGetSegmentCount(target) {
6114
+ let fields = new SortedSet(FieldPath$1.comparator);
6115
+ let hasArraySegment = false;
6116
+ for (const filter of target.filters) {
6117
+ for (const subFilter of filter.getFlattenedFilters()) {
6118
+ // __name__ is not an explicit segment of any index, so we don't need to
6119
+ // count it.
6120
+ if (subFilter.field.isKeyField()) {
6121
+ continue;
6122
+ }
6123
+ // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
6124
+ // For instance, it is possible to have an index for "a ARRAY a ASC". Even
6125
+ // though these are on the same field, they should be counted as two
6126
+ // separate segments in an index.
6127
+ if (subFilter.op === "array-contains" /* Operator.ARRAY_CONTAINS */ ||
6128
+ subFilter.op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) {
6129
+ hasArraySegment = true;
6130
+ }
6131
+ else {
6132
+ fields = fields.add(subFilter.field);
6133
+ }
6134
+ }
5938
6135
  }
5939
- for (let i = 0; i < left.position.length; i++) {
5940
- const leftPosition = left.position[i];
5941
- const rightPosition = right.position[i];
5942
- if (!valueEquals(leftPosition, rightPosition)) {
5943
- return false;
6136
+ for (const orderBy of target.orderBy) {
6137
+ // __name__ is not an explicit segment of any index, so we don't need to
6138
+ // count it.
6139
+ if (!orderBy.field.isKeyField()) {
6140
+ fields = fields.add(orderBy.field);
5944
6141
  }
5945
6142
  }
5946
- return true;
6143
+ return fields.size + (hasArraySegment ? 1 : 0);
6144
+ }
6145
+ function targetHasLimit(target) {
6146
+ return target.limit !== null;
5947
6147
  }
5948
6148
 
5949
6149
  /**
@@ -6028,20 +6228,9 @@ function getFirstOrderByField(query) {
6028
6228
  }
6029
6229
  function getInequalityFilterField(query) {
6030
6230
  for (const filter of query.filters) {
6031
- if (filter.isInequality()) {
6032
- return filter.field;
6033
- }
6034
- }
6035
- return null;
6036
- }
6037
- /**
6038
- * Checks if any of the provided Operators are included in the query and
6039
- * returns the first one that is, or null if none are.
6040
- */
6041
- function findFilterOperator(query, operators) {
6042
- for (const filter of query.filters) {
6043
- if (operators.indexOf(filter.op) >= 0) {
6044
- return filter.op;
6231
+ const result = filter.getFirstInequalityField();
6232
+ if (result !== null) {
6233
+ return result;
6045
6234
  }
6046
6235
  }
6047
6236
  return null;
@@ -6142,6 +6331,8 @@ function queryToTarget(query) {
6142
6331
  return queryImpl.memoizedTarget;
6143
6332
  }
6144
6333
  function queryWithAddedFilter(query, filter) {
6334
+ filter.getFirstInequalityField();
6335
+ getInequalityFilterField(query);
6145
6336
  const newFilters = query.filters.concat([filter]);
6146
6337
  return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt);
6147
6338
  }
@@ -6202,7 +6393,13 @@ function queryMatchesPathAndCollectionGroup(query, doc) {
6202
6393
  * in the results.
6203
6394
  */
6204
6395
  function queryMatchesOrderBy(query, doc) {
6205
- for (const orderBy of query.explicitOrderBy) {
6396
+ // We must use `queryOrderBy()` to get the list of all orderBys (both implicit and explicit).
6397
+ // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must
6398
+ // be taken into account. For example, the query "a > 1 || b==1" has an implicit "orderBy a" due
6399
+ // to the inequality, and is evaluated as "a > 1 orderBy a || b==1 orderBy a".
6400
+ // A document with content of {b:1} matches the filters, but does not match the orderBy because
6401
+ // it's missing the field 'a'.
6402
+ for (const orderBy of queryOrderBy(query)) {
6206
6403
  // order by key always matches
6207
6404
  if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) {
6208
6405
  return false;
@@ -8206,6 +8403,12 @@ const OPERATORS = (() => {
8206
8403
  ops["array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */] = 'ARRAY_CONTAINS_ANY';
8207
8404
  return ops;
8208
8405
  })();
8406
+ const COMPOSITE_OPERATORS = (() => {
8407
+ const ops = {};
8408
+ ops["and" /* CompositeOperator.AND */] = 'AND';
8409
+ ops["or" /* CompositeOperator.OR */] = 'OR';
8410
+ return ops;
8411
+ })();
8209
8412
  function assertPresent(value, description) {
8210
8413
  }
8211
8414
  /**
@@ -8731,7 +8934,7 @@ function toQueryTarget(serializer, target) {
8731
8934
  result.parent = toQueryPath(serializer, path.popLast());
8732
8935
  result.structuredQuery.from = [{ collectionId: path.lastSegment() }];
8733
8936
  }
8734
- const where = toFilter(target.filters);
8937
+ const where = toFilters(target.filters);
8735
8938
  if (where) {
8736
8939
  result.structuredQuery.where = where;
8737
8940
  }
@@ -8783,7 +8986,7 @@ function convertQueryTargetToQuery(target) {
8783
8986
  }
8784
8987
  let filterBy = [];
8785
8988
  if (query.where) {
8786
- filterBy = fromFilter(query.where);
8989
+ filterBy = fromFilters(query.where);
8787
8990
  }
8788
8991
  let orderBy = [];
8789
8992
  if (query.orderBy) {
@@ -8850,32 +9053,29 @@ function toTarget(serializer, targetData) {
8850
9053
  }
8851
9054
  return result;
8852
9055
  }
8853
- function toFilter(filters) {
9056
+ function toFilters(filters) {
8854
9057
  if (filters.length === 0) {
8855
9058
  return;
8856
9059
  }
8857
- const protos = filters.map(filter => {
8858
- return toUnaryOrFieldFilter(filter);
8859
- });
8860
- if (protos.length === 1) {
8861
- return protos[0];
9060
+ return toFilter(CompositeFilter.create(filters, "and" /* CompositeOperator.AND */));
9061
+ }
9062
+ function fromFilters(filter) {
9063
+ const result = fromFilter(filter);
9064
+ if (result instanceof CompositeFilter &&
9065
+ compositeFilterIsFlatConjunction(result)) {
9066
+ return result.getFilters();
8862
9067
  }
8863
- return { compositeFilter: { op: 'AND', filters: protos } };
9068
+ return [result];
8864
9069
  }
8865
9070
  function fromFilter(filter) {
8866
- if (!filter) {
8867
- return [];
8868
- }
8869
- else if (filter.unaryFilter !== undefined) {
8870
- return [fromUnaryFilter(filter)];
9071
+ if (filter.unaryFilter !== undefined) {
9072
+ return fromUnaryFilter(filter);
8871
9073
  }
8872
9074
  else if (filter.fieldFilter !== undefined) {
8873
- return [fromFieldFilter(filter)];
9075
+ return fromFieldFilter(filter);
8874
9076
  }
8875
9077
  else if (filter.compositeFilter !== undefined) {
8876
- return filter.compositeFilter
8877
- .filters.map(f => fromFilter(f))
8878
- .reduce((accum, current) => accum.concat(current));
9078
+ return fromCompositeFilter(filter);
8879
9079
  }
8880
9080
  else {
8881
9081
  return fail();
@@ -8931,6 +9131,9 @@ function fromDirection(dir) {
8931
9131
  function toOperatorName(op) {
8932
9132
  return OPERATORS[op];
8933
9133
  }
9134
+ function toCompositeOperatorName(op) {
9135
+ return COMPOSITE_OPERATORS[op];
9136
+ }
8934
9137
  function fromOperatorName(op) {
8935
9138
  switch (op) {
8936
9139
  case 'EQUAL':
@@ -8959,6 +9162,16 @@ function fromOperatorName(op) {
8959
9162
  return fail();
8960
9163
  }
8961
9164
  }
9165
+ function fromCompositeOperatorName(op) {
9166
+ switch (op) {
9167
+ case 'AND':
9168
+ return "and" /* CompositeOperator.AND */;
9169
+ case 'OR':
9170
+ return "or" /* CompositeOperator.OR */;
9171
+ default:
9172
+ return fail();
9173
+ }
9174
+ }
8962
9175
  function toFieldPathReference(path) {
8963
9176
  return { fieldPath: path.canonicalString() };
8964
9177
  }
@@ -8975,10 +9188,30 @@ function toPropertyOrder(orderBy) {
8975
9188
  function fromPropertyOrder(orderBy) {
8976
9189
  return new OrderBy(fromFieldPathReference(orderBy.field), fromDirection(orderBy.direction));
8977
9190
  }
8978
- function fromFieldFilter(filter) {
8979
- return FieldFilter.create(fromFieldPathReference(filter.fieldFilter.field), fromOperatorName(filter.fieldFilter.op), filter.fieldFilter.value);
8980
- }
8981
9191
  // visible for testing
9192
+ function toFilter(filter) {
9193
+ if (filter instanceof FieldFilter) {
9194
+ return toUnaryOrFieldFilter(filter);
9195
+ }
9196
+ else if (filter instanceof CompositeFilter) {
9197
+ return toCompositeFilter(filter);
9198
+ }
9199
+ else {
9200
+ return fail();
9201
+ }
9202
+ }
9203
+ function toCompositeFilter(filter) {
9204
+ const protos = filter.getFilters().map(filter => toFilter(filter));
9205
+ if (protos.length === 1) {
9206
+ return protos[0];
9207
+ }
9208
+ return {
9209
+ compositeFilter: {
9210
+ op: toCompositeOperatorName(filter.op),
9211
+ filters: protos
9212
+ }
9213
+ };
9214
+ }
8982
9215
  function toUnaryOrFieldFilter(filter) {
8983
9216
  if (filter.op === "==" /* Operator.EQUAL */) {
8984
9217
  if (isNanValue(filter.value)) {
@@ -9052,6 +9285,12 @@ function fromUnaryFilter(filter) {
9052
9285
  return fail();
9053
9286
  }
9054
9287
  }
9288
+ function fromFieldFilter(filter) {
9289
+ return FieldFilter.create(fromFieldPathReference(filter.fieldFilter.field), fromOperatorName(filter.fieldFilter.op), filter.fieldFilter.value);
9290
+ }
9291
+ function fromCompositeFilter(filter) {
9292
+ return CompositeFilter.create(filter.compositeFilter.filters.map(filter => fromFilter(filter)), fromCompositeOperatorName(filter.compositeFilter.op));
9293
+ }
9055
9294
  function toDocumentMask(fieldMask) {
9056
9295
  const canonicalFields = [];
9057
9296
  fieldMask.fields.forEach(field => canonicalFields.push(field.canonicalString()));
@@ -10298,6 +10537,7 @@ class TargetIndexMatcher {
10298
10537
  * omitted.
10299
10538
  */
10300
10539
  servedByIndex(index) {
10540
+ hardAssert(index.collectionGroup === this.collectionId);
10301
10541
  // If there is an array element, find a matching filter.
10302
10542
  const arraySegment = fieldIndexGetArraySegment(index);
10303
10543
  if (arraySegment !== undefined &&
@@ -10376,6 +10616,255 @@ class TargetIndexMatcher {
10376
10616
  }
10377
10617
  }
10378
10618
 
10619
+ /**
10620
+ * @license
10621
+ * Copyright 2022 Google LLC
10622
+ *
10623
+ * Licensed under the Apache License, Version 2.0 (the "License");
10624
+ * you may not use this file except in compliance with the License.
10625
+ * You may obtain a copy of the License at
10626
+ *
10627
+ * http://www.apache.org/licenses/LICENSE-2.0
10628
+ *
10629
+ * Unless required by applicable law or agreed to in writing, software
10630
+ * distributed under the License is distributed on an "AS IS" BASIS,
10631
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10632
+ * See the License for the specific language governing permissions and
10633
+ * limitations under the License.
10634
+ */
10635
+ /**
10636
+ * Provides utility functions that help with boolean logic transformations needed for handling
10637
+ * complex filters used in queries.
10638
+ */
10639
+ /**
10640
+ * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in
10641
+ * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given
10642
+ * input into a disjunction of equality filters and returns the expanded filter.
10643
+ */
10644
+ function computeInExpansion(filter) {
10645
+ var _a, _b;
10646
+ hardAssert(filter instanceof FieldFilter || filter instanceof CompositeFilter);
10647
+ if (filter instanceof FieldFilter) {
10648
+ if (filter instanceof InFilter) {
10649
+ const expandedFilters = ((_b = (_a = filter.value.arrayValue) === null || _a === void 0 ? void 0 : _a.values) === null || _b === void 0 ? void 0 : _b.map(value => FieldFilter.create(filter.field, "==" /* Operator.EQUAL */, value))) || [];
10650
+ return CompositeFilter.create(expandedFilters, "or" /* CompositeOperator.OR */);
10651
+ }
10652
+ else {
10653
+ // We have reached other kinds of field filters.
10654
+ return filter;
10655
+ }
10656
+ }
10657
+ // We have a composite filter.
10658
+ const expandedFilters = filter.filters.map(subfilter => computeInExpansion(subfilter));
10659
+ return CompositeFilter.create(expandedFilters, filter.op);
10660
+ }
10661
+ /**
10662
+ * Given a composite filter, returns the list of terms in its disjunctive normal form.
10663
+ *
10664
+ * <p>Each element in the return value is one term of the resulting DNF. For instance: For the
10665
+ * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list
10666
+ * with two elements: a composite filter that performs (A && C), and a composite filter that
10667
+ * performs (B && C).
10668
+ *
10669
+ * @param filter the composite filter to calculate DNF transform for.
10670
+ * @return the terms in the DNF transform.
10671
+ */
10672
+ function getDnfTerms(filter) {
10673
+ if (filter.getFilters().length === 0) {
10674
+ return [];
10675
+ }
10676
+ const result = computeDistributedNormalForm(computeInExpansion(filter));
10677
+ hardAssert(isDisjunctiveNormalForm(result));
10678
+ if (isSingleFieldFilter(result) || isFlatConjunction(result)) {
10679
+ return [result];
10680
+ }
10681
+ return result.getFilters();
10682
+ }
10683
+ /** Returns true if the given filter is a single field filter. e.g. (a == 10). */
10684
+ function isSingleFieldFilter(filter) {
10685
+ return filter instanceof FieldFilter;
10686
+ }
10687
+ /**
10688
+ * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10
10689
+ * && b == 20)
10690
+ */
10691
+ function isFlatConjunction(filter) {
10692
+ return (filter instanceof CompositeFilter &&
10693
+ compositeFilterIsFlatConjunction(filter));
10694
+ }
10695
+ /**
10696
+ * Returns whether or not the given filter is in disjunctive normal form (DNF).
10697
+ *
10698
+ * <p>In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical
10699
+ * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.
10700
+ *
10701
+ * <p>For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form
10702
+ */
10703
+ function isDisjunctiveNormalForm(filter) {
10704
+ return (isSingleFieldFilter(filter) ||
10705
+ isFlatConjunction(filter) ||
10706
+ isDisjunctionOfFieldFiltersAndFlatConjunctions(filter));
10707
+ }
10708
+ /**
10709
+ * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and
10710
+ * field filters. e.g. (a == 10) || (b==20 && c==30)
10711
+ */
10712
+ function isDisjunctionOfFieldFiltersAndFlatConjunctions(filter) {
10713
+ if (filter instanceof CompositeFilter) {
10714
+ if (compositeFilterIsDisjunction(filter)) {
10715
+ for (const subFilter of filter.getFilters()) {
10716
+ if (!isSingleFieldFilter(subFilter) && !isFlatConjunction(subFilter)) {
10717
+ return false;
10718
+ }
10719
+ }
10720
+ return true;
10721
+ }
10722
+ }
10723
+ return false;
10724
+ }
10725
+ function computeDistributedNormalForm(filter) {
10726
+ hardAssert(filter instanceof FieldFilter || filter instanceof CompositeFilter);
10727
+ if (filter instanceof FieldFilter) {
10728
+ return filter;
10729
+ }
10730
+ if (filter.filters.length === 1) {
10731
+ return computeDistributedNormalForm(filter.filters[0]);
10732
+ }
10733
+ // Compute DNF for each of the subfilters first
10734
+ const result = filter.filters.map(subfilter => computeDistributedNormalForm(subfilter));
10735
+ let newFilter = CompositeFilter.create(result, filter.op);
10736
+ newFilter = applyAssociation(newFilter);
10737
+ if (isDisjunctiveNormalForm(newFilter)) {
10738
+ return newFilter;
10739
+ }
10740
+ hardAssert(newFilter instanceof CompositeFilter);
10741
+ hardAssert(compositeFilterIsConjunction(newFilter));
10742
+ hardAssert(newFilter.filters.length > 1);
10743
+ return newFilter.filters.reduce((runningResult, filter) => applyDistribution(runningResult, filter));
10744
+ }
10745
+ function applyDistribution(lhs, rhs) {
10746
+ hardAssert(lhs instanceof FieldFilter || lhs instanceof CompositeFilter);
10747
+ hardAssert(rhs instanceof FieldFilter || rhs instanceof CompositeFilter);
10748
+ let result;
10749
+ if (lhs instanceof FieldFilter) {
10750
+ if (rhs instanceof FieldFilter) {
10751
+ // FieldFilter FieldFilter
10752
+ result = applyDistributionFieldFilters(lhs, rhs);
10753
+ }
10754
+ else {
10755
+ // FieldFilter CompositeFilter
10756
+ result = applyDistributionFieldAndCompositeFilters(lhs, rhs);
10757
+ }
10758
+ }
10759
+ else {
10760
+ if (rhs instanceof FieldFilter) {
10761
+ // CompositeFilter FieldFilter
10762
+ result = applyDistributionFieldAndCompositeFilters(rhs, lhs);
10763
+ }
10764
+ else {
10765
+ // CompositeFilter CompositeFilter
10766
+ result = applyDistributionCompositeFilters(lhs, rhs);
10767
+ }
10768
+ }
10769
+ return applyAssociation(result);
10770
+ }
10771
+ function applyDistributionFieldFilters(lhs, rhs) {
10772
+ // Conjunction distribution for two field filters is the conjunction of them.
10773
+ return CompositeFilter.create([lhs, rhs], "and" /* CompositeOperator.AND */);
10774
+ }
10775
+ function applyDistributionCompositeFilters(lhs, rhs) {
10776
+ hardAssert(lhs.filters.length > 0 && rhs.filters.length > 0);
10777
+ // There are four cases:
10778
+ // (A & B) & (C & D) --> (A & B & C & D)
10779
+ // (A & B) & (C | D) --> (A & B & C) | (A & B & D)
10780
+ // (A | B) & (C & D) --> (C & D & A) | (C & D & B)
10781
+ // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)
10782
+ // Case 1 is a merge.
10783
+ if (compositeFilterIsConjunction(lhs) && compositeFilterIsConjunction(rhs)) {
10784
+ return compositeFilterWithAddedFilters(lhs, rhs.getFilters());
10785
+ }
10786
+ // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases
10787
+ // we should take each element of the disjunction and distribute it over the other side, and
10788
+ // return the disjunction of the distribution results.
10789
+ const disjunctionSide = compositeFilterIsDisjunction(lhs) ? lhs : rhs;
10790
+ const otherSide = compositeFilterIsDisjunction(lhs) ? rhs : lhs;
10791
+ const results = disjunctionSide.filters.map(subfilter => applyDistribution(subfilter, otherSide));
10792
+ return CompositeFilter.create(results, "or" /* CompositeOperator.OR */);
10793
+ }
10794
+ function applyDistributionFieldAndCompositeFilters(fieldFilter, compositeFilter) {
10795
+ // There are two cases:
10796
+ // A & (B & C) --> (A & B & C)
10797
+ // A & (B | C) --> (A & B) | (A & C)
10798
+ if (compositeFilterIsConjunction(compositeFilter)) {
10799
+ // Case 1
10800
+ return compositeFilterWithAddedFilters(compositeFilter, fieldFilter.getFilters());
10801
+ }
10802
+ else {
10803
+ // Case 2
10804
+ const newFilters = compositeFilter.filters.map(subfilter => applyDistribution(fieldFilter, subfilter));
10805
+ return CompositeFilter.create(newFilters, "or" /* CompositeOperator.OR */);
10806
+ }
10807
+ }
10808
+ /**
10809
+ * Applies the associativity property to the given filter and returns the resulting filter.
10810
+ *
10811
+ * <ul>
10812
+ * <li>A | (B | C) == (A | B) | C == (A | B | C)
10813
+ * <li>A & (B & C) == (A & B) & C == (A & B & C)
10814
+ * </ul>
10815
+ *
10816
+ * <p>For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic
10817
+ */
10818
+ function applyAssociation(filter) {
10819
+ hardAssert(filter instanceof FieldFilter || filter instanceof CompositeFilter);
10820
+ if (filter instanceof FieldFilter) {
10821
+ return filter;
10822
+ }
10823
+ const filters = filter.getFilters();
10824
+ // If the composite filter only contains 1 filter, apply associativity to it.
10825
+ if (filters.length === 1) {
10826
+ return applyAssociation(filters[0]);
10827
+ }
10828
+ // Associativity applied to a flat composite filter results is itself.
10829
+ if (compositeFilterIsFlat(filter)) {
10830
+ return filter;
10831
+ }
10832
+ // First apply associativity to all subfilters. This will in turn recursively apply
10833
+ // associativity to all nested composite filters and field filters.
10834
+ const updatedFilters = filters.map(subfilter => applyAssociation(subfilter));
10835
+ // For composite subfilters that perform the same kind of logical operation as `compositeFilter`
10836
+ // take out their filters and add them to `compositeFilter`. For example:
10837
+ // compositeFilter = (A | (B | C | D))
10838
+ // compositeSubfilter = (B | C | D)
10839
+ // Result: (A | B | C | D)
10840
+ // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been
10841
+ // added to the top-level "compositeFilter".
10842
+ const newSubfilters = [];
10843
+ updatedFilters.forEach(subfilter => {
10844
+ if (subfilter instanceof FieldFilter) {
10845
+ newSubfilters.push(subfilter);
10846
+ }
10847
+ else if (subfilter instanceof CompositeFilter) {
10848
+ if (subfilter.op === filter.op) {
10849
+ // compositeFilter: (A | (B | C))
10850
+ // compositeSubfilter: (B | C)
10851
+ // Result: (A | B | C)
10852
+ newSubfilters.push(...subfilter.filters);
10853
+ }
10854
+ else {
10855
+ // compositeFilter: (A | (B & C))
10856
+ // compositeSubfilter: (B & C)
10857
+ // Result: (A | (B & C))
10858
+ newSubfilters.push(subfilter);
10859
+ }
10860
+ }
10861
+ });
10862
+ if (newSubfilters.length === 1) {
10863
+ return newSubfilters[0];
10864
+ }
10865
+ return CompositeFilter.create(newSubfilters, filter.op);
10866
+ }
10867
+
10379
10868
  /**
10380
10869
  * @license
10381
10870
  * Copyright 2019 Google LLC
@@ -10643,8 +11132,14 @@ class IndexedDbIndexManager {
10643
11132
  if (subTargets) {
10644
11133
  return subTargets;
10645
11134
  }
10646
- // TODO(orquery): Implement DNF transform
10647
- subTargets = [target];
11135
+ if (target.filters.length === 0) {
11136
+ subTargets = [target];
11137
+ }
11138
+ else {
11139
+ // There is an implicit AND operation between all the filters stored in the target
11140
+ const dnf = getDnfTerms(CompositeFilter.create(target.filters, "and" /* CompositeOperator.AND */));
11141
+ subTargets = dnf.map(term => newTarget(target.path, target.collectionGroup, target.orderBy, term.getFilters(), target.limit, target.startAt, target.endAt));
11142
+ }
10648
11143
  this.targetToDnfSubTargets.set(target, subTargets);
10649
11144
  return subTargets;
10650
11145
  }
@@ -10703,7 +11198,8 @@ class IndexedDbIndexManager {
10703
11198
  }
10704
11199
  getIndexType(transaction, target) {
10705
11200
  let indexType = 2 /* IndexType.FULL */;
10706
- return PersistencePromise.forEach(this.getSubTargets(target), (target) => {
11201
+ const subTargets = this.getSubTargets(target);
11202
+ return PersistencePromise.forEach(subTargets, (target) => {
10707
11203
  return this.getFieldIndex(transaction, target).next(index => {
10708
11204
  if (!index) {
10709
11205
  indexType = 0 /* IndexType.NONE */;
@@ -10713,7 +11209,17 @@ class IndexedDbIndexManager {
10713
11209
  indexType = 1 /* IndexType.PARTIAL */;
10714
11210
  }
10715
11211
  });
10716
- }).next(() => indexType);
11212
+ }).next(() => {
11213
+ // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider
11214
+ // OR queries that have a `limit` to have a partial index. For such queries we perform sorting
11215
+ // and apply the limit in memory as a post-processing step.
11216
+ if (targetHasLimit(target) &&
11217
+ subTargets.length > 1 &&
11218
+ indexType === 2 /* IndexType.FULL */) {
11219
+ return 1 /* IndexType.PARTIAL */;
11220
+ }
11221
+ return indexType;
11222
+ });
10717
11223
  }
10718
11224
  /**
10719
11225
  * Returns the byte encoded form of the directional values in the field index.
@@ -10751,15 +11257,15 @@ class IndexedDbIndexManager {
10751
11257
  * Encodes the given field values according to the specification in `target`.
10752
11258
  * For IN queries, a list of possible values is returned.
10753
11259
  */
10754
- encodeValues(fieldIndex, target, bound) {
10755
- if (bound === null) {
11260
+ encodeValues(fieldIndex, target, values) {
11261
+ if (values === null) {
10756
11262
  return [];
10757
11263
  }
10758
11264
  let encoders = [];
10759
11265
  encoders.push(new IndexByteEncoder());
10760
- let boundIdx = 0;
11266
+ let valueIdx = 0;
10761
11267
  for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) {
10762
- const value = bound[boundIdx++];
11268
+ const value = values[valueIdx++];
10763
11269
  for (const encoder of encoders) {
10764
11270
  if (this.isInFilter(target, segment.fieldPath) && isArray(value)) {
10765
11271
  encoders = this.expandIndexValues(encoders, segment, value);
@@ -10999,24 +11505,36 @@ class IndexedDbIndexManager {
10999
11505
  bounds.push(upper);
11000
11506
  const ranges = [];
11001
11507
  for (let i = 0; i < bounds.length; i += 2) {
11002
- ranges.push(IDBKeyRange.bound([
11508
+ // If we encounter two bounds that will create an unmatchable key range,
11509
+ // then we return an empty set of key ranges.
11510
+ if (this.isRangeMatchable(bounds[i], bounds[i + 1])) {
11511
+ return [];
11512
+ }
11513
+ const lowerBound = [
11003
11514
  bounds[i].indexId,
11004
11515
  this.uid,
11005
11516
  bounds[i].arrayValue,
11006
11517
  bounds[i].directionalValue,
11007
11518
  EMPTY_VALUE,
11008
11519
  []
11009
- ], [
11520
+ ];
11521
+ const upperBound = [
11010
11522
  bounds[i + 1].indexId,
11011
11523
  this.uid,
11012
11524
  bounds[i + 1].arrayValue,
11013
11525
  bounds[i + 1].directionalValue,
11014
11526
  EMPTY_VALUE,
11015
11527
  []
11016
- ]));
11528
+ ];
11529
+ ranges.push(IDBKeyRange.bound(lowerBound, upperBound));
11017
11530
  }
11018
11531
  return ranges;
11019
11532
  }
11533
+ isRangeMatchable(lowerBound, upperBound) {
11534
+ // If lower bound is greater than the upper bound, then the key
11535
+ // range can never be matched.
11536
+ return indexEntryComparator(lowerBound, upperBound) > 0;
11537
+ }
11020
11538
  getMinOffsetFromCollectionGroup(transaction, collectionGroup) {
11021
11539
  return this.getFieldIndexes(transaction, collectionGroup).next(getMinOffsetFromFieldIndexes);
11022
11540
  }
@@ -19856,7 +20374,8 @@ const nested = {
19856
20374
  Operator: {
19857
20375
  values: {
19858
20376
  OPERATOR_UNSPECIFIED: 0,
19859
- AND: 1
20377
+ AND: 1,
20378
+ OR: 2
19860
20379
  }
19861
20380
  }
19862
20381
  }
@@ -28061,159 +28580,329 @@ function validateHasExplicitOrderByForLimitToLast(query) {
28061
28580
  throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause');
28062
28581
  }
28063
28582
  }
28583
+ /**
28584
+ * An `AppliableConstraint` is an abstraction of a constraint that can be applied
28585
+ * to a Firestore query.
28586
+ */
28587
+ class AppliableConstraint {
28588
+ }
28064
28589
  /**
28065
28590
  * A `QueryConstraint` is used to narrow the set of documents returned by a
28066
28591
  * Firestore query. `QueryConstraint`s are created by invoking {@link where},
28067
- * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link
28068
- * endBefore:1}, {@link (endAt:1)}, {@link limit} or {@link limitToLast} and
28592
+ * {@link orderBy}, {@link startAt}, {@link startAfter}, {@link
28593
+ * endBefore}, {@link endAt}, {@link limit}, {@link limitToLast} and
28069
28594
  * can then be passed to {@link query} to create a new query instance that
28070
28595
  * also contains this `QueryConstraint`.
28071
28596
  */
28072
- class QueryConstraint {
28597
+ class QueryConstraint extends AppliableConstraint {
28073
28598
  }
28074
- /**
28075
- * Creates a new immutable instance of {@link Query} that is extended to also include
28076
- * additional query constraints.
28077
- *
28078
- * @param query - The {@link Query} instance to use as a base for the new constraints.
28079
- * @param queryConstraints - The list of {@link QueryConstraint}s to apply.
28080
- * @throws if any of the provided query constraints cannot be combined with the
28081
- * existing or new constraints.
28082
- */
28083
- function query(query, ...queryConstraints) {
28599
+ function query(query, queryConstraint, ...additionalQueryConstraints) {
28600
+ let queryConstraints = [];
28601
+ if (queryConstraint instanceof AppliableConstraint) {
28602
+ queryConstraints.push(queryConstraint);
28603
+ }
28604
+ queryConstraints = queryConstraints.concat(additionalQueryConstraints);
28605
+ validateQueryConstraintArray(queryConstraints);
28084
28606
  for (const constraint of queryConstraints) {
28085
28607
  query = constraint._apply(query);
28086
28608
  }
28087
28609
  return query;
28088
28610
  }
28089
- class QueryFilterConstraint extends QueryConstraint {
28611
+ /**
28612
+ * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by
28613
+ * a Firestore query by filtering on one or more document fields.
28614
+ * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then
28615
+ * be passed to {@link query} to create a new query instance that also contains
28616
+ * this `QueryFieldFilterConstraint`.
28617
+ */
28618
+ class QueryFieldFilterConstraint extends QueryConstraint {
28619
+ /**
28620
+ * @internal
28621
+ */
28090
28622
  constructor(_field, _op, _value) {
28091
28623
  super();
28092
28624
  this._field = _field;
28093
28625
  this._op = _op;
28094
28626
  this._value = _value;
28627
+ /** The type of this query constraint */
28095
28628
  this.type = 'where';
28096
28629
  }
28630
+ static _create(_field, _op, _value) {
28631
+ return new QueryFieldFilterConstraint(_field, _op, _value);
28632
+ }
28097
28633
  _apply(query) {
28634
+ const filter = this._parse(query);
28635
+ validateNewFieldFilter(query._query, filter);
28636
+ return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter));
28637
+ }
28638
+ _parse(query) {
28098
28639
  const reader = newUserDataReader(query.firestore);
28099
28640
  const filter = newQueryFilter(query._query, 'where', reader, query.firestore._databaseId, this._field, this._op, this._value);
28100
- return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter));
28641
+ return filter;
28101
28642
  }
28102
28643
  }
28103
28644
  /**
28104
- * Creates a {@link QueryConstraint} that enforces that documents must contain the
28105
- * specified field and that the value should satisfy the relation constraint
28106
- * provided.
28645
+ * Creates a {@link QueryFieldFilterConstraint} that enforces that documents
28646
+ * must contain the specified field and that the value should satisfy the
28647
+ * relation constraint provided.
28107
28648
  *
28108
28649
  * @param fieldPath - The path to compare
28109
28650
  * @param opStr - The operation string (e.g "&lt;", "&lt;=", "==", "&lt;",
28110
28651
  * "&lt;=", "!=").
28111
28652
  * @param value - The value for comparison
28112
- * @returns The created {@link Query}.
28653
+ * @returns The created {@link QueryFieldFilterConstraint}.
28113
28654
  */
28114
28655
  function where(fieldPath, opStr, value) {
28115
28656
  const op = opStr;
28116
28657
  const field = fieldPathFromArgument('where', fieldPath);
28117
- return new QueryFilterConstraint(field, op, value);
28658
+ return QueryFieldFilterConstraint._create(field, op, value);
28659
+ }
28660
+ /**
28661
+ * A `QueryCompositeFilterConstraint` is used to narrow the set of documents
28662
+ * returned by a Firestore query by performing the logical OR or AND of multiple
28663
+ * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.
28664
+ * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or
28665
+ * {@link and} and can then be passed to {@link query} to create a new query
28666
+ * instance that also contains the `QueryCompositeFilterConstraint`.
28667
+ * @internal TODO remove this internal tag with OR Query support in the server
28668
+ */
28669
+ class QueryCompositeFilterConstraint extends AppliableConstraint {
28670
+ /**
28671
+ * @internal
28672
+ */
28673
+ constructor(
28674
+ /** The type of this query constraint */
28675
+ type, _queryConstraints) {
28676
+ super();
28677
+ this.type = type;
28678
+ this._queryConstraints = _queryConstraints;
28679
+ }
28680
+ static _create(type, _queryConstraints) {
28681
+ return new QueryCompositeFilterConstraint(type, _queryConstraints);
28682
+ }
28683
+ _parse(query) {
28684
+ const parsedFilters = this._queryConstraints
28685
+ .map(queryConstraint => {
28686
+ return queryConstraint._parse(query);
28687
+ })
28688
+ .filter(parsedFilter => parsedFilter.getFilters().length > 0);
28689
+ if (parsedFilters.length === 1) {
28690
+ return parsedFilters[0];
28691
+ }
28692
+ return CompositeFilter.create(parsedFilters, this._getOperator());
28693
+ }
28694
+ _apply(query) {
28695
+ const parsedFilter = this._parse(query);
28696
+ if (parsedFilter.getFilters().length === 0) {
28697
+ // Return the existing query if not adding any more filters (e.g. an empty
28698
+ // composite filter).
28699
+ return query;
28700
+ }
28701
+ validateNewFilter(query._query, parsedFilter);
28702
+ return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, parsedFilter));
28703
+ }
28704
+ _getQueryConstraints() {
28705
+ return this._queryConstraints;
28706
+ }
28707
+ _getOperator() {
28708
+ return this.type === 'and' ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */;
28709
+ }
28710
+ }
28711
+ /**
28712
+ * Creates a {@link QueryCompositeFilterConstraint} that performs a logical OR
28713
+ * of all the provided {@link QueryFilterConstraint}s.
28714
+ *
28715
+ * @param queryConstraints - Optional. The {@link QueryFilterConstraint}s
28716
+ * for OR operation. These must be created with calls to {@link where},
28717
+ * {@link or}, or {@link and}.
28718
+ * @returns The created {@link QueryCompositeFilterConstraint}.
28719
+ * @internal TODO remove this internal tag with OR Query support in the server
28720
+ */
28721
+ function or(...queryConstraints) {
28722
+ // Only support QueryFilterConstraints
28723
+ queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('or', queryConstraint));
28724
+ return QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */, queryConstraints);
28725
+ }
28726
+ /**
28727
+ * Creates a {@link QueryCompositeFilterConstraint} that performs a logical AND
28728
+ * of all the provided {@link QueryFilterConstraint}s.
28729
+ *
28730
+ * @param queryConstraints - Optional. The {@link QueryFilterConstraint}s
28731
+ * for AND operation. These must be created with calls to {@link where},
28732
+ * {@link or}, or {@link and}.
28733
+ * @returns The created {@link QueryCompositeFilterConstraint}.
28734
+ * @internal TODO remove this internal tag with OR Query support in the server
28735
+ */
28736
+ function and(...queryConstraints) {
28737
+ // Only support QueryFilterConstraints
28738
+ queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('and', queryConstraint));
28739
+ return QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */, queryConstraints);
28118
28740
  }
28741
+ /**
28742
+ * A `QueryOrderByConstraint` is used to sort the set of documents returned by a
28743
+ * Firestore query. `QueryOrderByConstraint`s are created by invoking
28744
+ * {@link orderBy} and can then be passed to {@link query} to create a new query
28745
+ * instance that also contains this `QueryOrderByConstraint`.
28746
+ *
28747
+ * Note: Documents that do not contain the orderBy field will not be present in
28748
+ * the query result.
28749
+ */
28119
28750
  class QueryOrderByConstraint extends QueryConstraint {
28751
+ /**
28752
+ * @internal
28753
+ */
28120
28754
  constructor(_field, _direction) {
28121
28755
  super();
28122
28756
  this._field = _field;
28123
28757
  this._direction = _direction;
28758
+ /** The type of this query constraint */
28124
28759
  this.type = 'orderBy';
28125
28760
  }
28761
+ static _create(_field, _direction) {
28762
+ return new QueryOrderByConstraint(_field, _direction);
28763
+ }
28126
28764
  _apply(query) {
28127
28765
  const orderBy = newQueryOrderBy(query._query, this._field, this._direction);
28128
28766
  return new Query(query.firestore, query.converter, queryWithAddedOrderBy(query._query, orderBy));
28129
28767
  }
28130
28768
  }
28131
28769
  /**
28132
- * Creates a {@link QueryConstraint} that sorts the query result by the
28770
+ * Creates a {@link QueryOrderByConstraint} that sorts the query result by the
28133
28771
  * specified field, optionally in descending order instead of ascending.
28134
28772
  *
28773
+ * Note: Documents that do not contain the specified field will not be present
28774
+ * in the query result.
28775
+ *
28135
28776
  * @param fieldPath - The field to sort by.
28136
28777
  * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If
28137
28778
  * not specified, order will be ascending.
28138
- * @returns The created {@link Query}.
28779
+ * @returns The created {@link QueryOrderByConstraint}.
28139
28780
  */
28140
28781
  function orderBy(fieldPath, directionStr = 'asc') {
28141
28782
  const direction = directionStr;
28142
28783
  const path = fieldPathFromArgument('orderBy', fieldPath);
28143
- return new QueryOrderByConstraint(path, direction);
28784
+ return QueryOrderByConstraint._create(path, direction);
28144
28785
  }
28786
+ /**
28787
+ * A `QueryLimitConstraint` is used to limit the number of documents returned by
28788
+ * a Firestore query.
28789
+ * `QueryLimitConstraint`s are created by invoking {@link limit} or
28790
+ * {@link limitToLast} and can then be passed to {@link query} to create a new
28791
+ * query instance that also contains this `QueryLimitConstraint`.
28792
+ */
28145
28793
  class QueryLimitConstraint extends QueryConstraint {
28146
- constructor(type, _limit, _limitType) {
28794
+ /**
28795
+ * @internal
28796
+ */
28797
+ constructor(
28798
+ /** The type of this query constraint */
28799
+ type, _limit, _limitType) {
28147
28800
  super();
28148
28801
  this.type = type;
28149
28802
  this._limit = _limit;
28150
28803
  this._limitType = _limitType;
28151
28804
  }
28805
+ static _create(type, _limit, _limitType) {
28806
+ return new QueryLimitConstraint(type, _limit, _limitType);
28807
+ }
28152
28808
  _apply(query) {
28153
28809
  return new Query(query.firestore, query.converter, queryWithLimit(query._query, this._limit, this._limitType));
28154
28810
  }
28155
28811
  }
28156
28812
  /**
28157
- * Creates a {@link QueryConstraint} that only returns the first matching documents.
28813
+ * Creates a {@link QueryLimitConstraint} that only returns the first matching
28814
+ * documents.
28158
28815
  *
28159
28816
  * @param limit - The maximum number of items to return.
28160
- * @returns The created {@link Query}.
28817
+ * @returns The created {@link QueryLimitConstraint}.
28161
28818
  */
28162
28819
  function limit(limit) {
28163
28820
  validatePositiveNumber('limit', limit);
28164
- return new QueryLimitConstraint('limit', limit, "F" /* LimitType.First */);
28821
+ return QueryLimitConstraint._create('limit', limit, "F" /* LimitType.First */);
28165
28822
  }
28166
28823
  /**
28167
- * Creates a {@link QueryConstraint} that only returns the last matching documents.
28824
+ * Creates a {@link QueryLimitConstraint} that only returns the last matching
28825
+ * documents.
28168
28826
  *
28169
28827
  * You must specify at least one `orderBy` clause for `limitToLast` queries,
28170
28828
  * otherwise an exception will be thrown during execution.
28171
28829
  *
28172
28830
  * @param limit - The maximum number of items to return.
28173
- * @returns The created {@link Query}.
28831
+ * @returns The created {@link QueryLimitConstraint}.
28174
28832
  */
28175
28833
  function limitToLast(limit) {
28176
28834
  validatePositiveNumber('limitToLast', limit);
28177
- return new QueryLimitConstraint('limitToLast', limit, "L" /* LimitType.Last */);
28835
+ return QueryLimitConstraint._create('limitToLast', limit, "L" /* LimitType.Last */);
28178
28836
  }
28837
+ /**
28838
+ * A `QueryStartAtConstraint` is used to exclude documents from the start of a
28839
+ * result set returned by a Firestore query.
28840
+ * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or
28841
+ * {@link (startAfter:1)} and can then be passed to {@link query} to create a
28842
+ * new query instance that also contains this `QueryStartAtConstraint`.
28843
+ */
28179
28844
  class QueryStartAtConstraint extends QueryConstraint {
28180
- constructor(type, _docOrFields, _inclusive) {
28845
+ /**
28846
+ * @internal
28847
+ */
28848
+ constructor(
28849
+ /** The type of this query constraint */
28850
+ type, _docOrFields, _inclusive) {
28181
28851
  super();
28182
28852
  this.type = type;
28183
28853
  this._docOrFields = _docOrFields;
28184
28854
  this._inclusive = _inclusive;
28185
28855
  }
28856
+ static _create(type, _docOrFields, _inclusive) {
28857
+ return new QueryStartAtConstraint(type, _docOrFields, _inclusive);
28858
+ }
28186
28859
  _apply(query) {
28187
28860
  const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive);
28188
28861
  return new Query(query.firestore, query.converter, queryWithStartAt(query._query, bound));
28189
28862
  }
28190
28863
  }
28191
28864
  function startAt(...docOrFields) {
28192
- return new QueryStartAtConstraint('startAt', docOrFields,
28865
+ return QueryStartAtConstraint._create('startAt', docOrFields,
28193
28866
  /*inclusive=*/ true);
28194
28867
  }
28195
28868
  function startAfter(...docOrFields) {
28196
- return new QueryStartAtConstraint('startAfter', docOrFields,
28869
+ return QueryStartAtConstraint._create('startAfter', docOrFields,
28197
28870
  /*inclusive=*/ false);
28198
28871
  }
28872
+ /**
28873
+ * A `QueryEndAtConstraint` is used to exclude documents from the end of a
28874
+ * result set returned by a Firestore query.
28875
+ * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or
28876
+ * {@link (endBefore:1)} and can then be passed to {@link query} to create a new
28877
+ * query instance that also contains this `QueryEndAtConstraint`.
28878
+ */
28199
28879
  class QueryEndAtConstraint extends QueryConstraint {
28200
- constructor(type, _docOrFields, _inclusive) {
28880
+ /**
28881
+ * @internal
28882
+ */
28883
+ constructor(
28884
+ /** The type of this query constraint */
28885
+ type, _docOrFields, _inclusive) {
28201
28886
  super();
28202
28887
  this.type = type;
28203
28888
  this._docOrFields = _docOrFields;
28204
28889
  this._inclusive = _inclusive;
28205
28890
  }
28891
+ static _create(type, _docOrFields, _inclusive) {
28892
+ return new QueryEndAtConstraint(type, _docOrFields, _inclusive);
28893
+ }
28206
28894
  _apply(query) {
28207
28895
  const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive);
28208
28896
  return new Query(query.firestore, query.converter, queryWithEndAt(query._query, bound));
28209
28897
  }
28210
28898
  }
28211
28899
  function endBefore(...docOrFields) {
28212
- return new QueryEndAtConstraint('endBefore', docOrFields,
28900
+ return QueryEndAtConstraint._create('endBefore', docOrFields,
28213
28901
  /*inclusive=*/ false);
28214
28902
  }
28215
28903
  function endAt(...docOrFields) {
28216
- return new QueryEndAtConstraint('endAt', docOrFields, /*inclusive=*/ true);
28904
+ return QueryEndAtConstraint._create('endAt', docOrFields,
28905
+ /*inclusive=*/ true);
28217
28906
  }
28218
28907
  /** Helper function to create a bound from a document or fields */
28219
28908
  function newQueryBoundFromDocOrFields(query, methodName, docOrFields, inclusive) {
@@ -28254,7 +28943,6 @@ function newQueryFilter(query, methodName, dataReader, databaseId, fieldPath, op
28254
28943
  /* allowArrays= */ op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */);
28255
28944
  }
28256
28945
  const filter = FieldFilter.create(fieldPath, op, fieldValue);
28257
- validateNewFilter(query, filter);
28258
28946
  return filter;
28259
28947
  }
28260
28948
  function newQueryOrderBy(query, fieldPath, direction) {
@@ -28453,33 +29141,55 @@ function conflictingOps(op) {
28453
29141
  return [];
28454
29142
  }
28455
29143
  }
28456
- function validateNewFilter(query, filter) {
28457
- if (filter.isInequality()) {
28458
- const existingField = getInequalityFilterField(query);
28459
- if (existingField !== null && !existingField.isEqual(filter.field)) {
29144
+ function validateNewFieldFilter(query, fieldFilter) {
29145
+ if (fieldFilter.isInequality()) {
29146
+ const existingInequality = getInequalityFilterField(query);
29147
+ const newInequality = fieldFilter.field;
29148
+ if (existingInequality !== null &&
29149
+ !existingInequality.isEqual(newInequality)) {
28460
29150
  throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. All where filters with an inequality' +
28461
29151
  ' (<, <=, !=, not-in, >, or >=) must be on the same field. But you have' +
28462
- ` inequality filters on '${existingField.toString()}'` +
28463
- ` and '${filter.field.toString()}'`);
29152
+ ` inequality filters on '${existingInequality.toString()}'` +
29153
+ ` and '${newInequality.toString()}'`);
28464
29154
  }
28465
29155
  const firstOrderByField = getFirstOrderByField(query);
28466
29156
  if (firstOrderByField !== null) {
28467
- validateOrderByAndInequalityMatch(query, filter.field, firstOrderByField);
29157
+ validateOrderByAndInequalityMatch(query, newInequality, firstOrderByField);
28468
29158
  }
28469
29159
  }
28470
- const conflictingOp = findFilterOperator(query, conflictingOps(filter.op));
29160
+ const conflictingOp = findOpInsideFilters(query.filters, conflictingOps(fieldFilter.op));
28471
29161
  if (conflictingOp !== null) {
28472
29162
  // Special case when it's a duplicate op to give a slightly clearer error message.
28473
- if (conflictingOp === filter.op) {
29163
+ if (conflictingOp === fieldFilter.op) {
28474
29164
  throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You cannot use more than one ' +
28475
- `'${filter.op.toString()}' filter.`);
29165
+ `'${fieldFilter.op.toString()}' filter.`);
28476
29166
  }
28477
29167
  else {
28478
- throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You cannot use '${filter.op.toString()}' filters ` +
29168
+ throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` +
28479
29169
  `with '${conflictingOp.toString()}' filters.`);
28480
29170
  }
28481
29171
  }
28482
29172
  }
29173
+ function validateNewFilter(query, filter) {
29174
+ let testQuery = query;
29175
+ const subFilters = filter.getFlattenedFilters();
29176
+ for (const subFilter of subFilters) {
29177
+ validateNewFieldFilter(testQuery, subFilter);
29178
+ testQuery = queryWithAddedFilter(testQuery, subFilter);
29179
+ }
29180
+ }
29181
+ // Checks if any of the provided filter operators are included in the given list of filters and
29182
+ // returns the first one that is, or null if none are.
29183
+ function findOpInsideFilters(filters, operators) {
29184
+ for (const filter of filters) {
29185
+ for (const fieldFilter of filter.getFlattenedFilters()) {
29186
+ if (operators.indexOf(fieldFilter.op) >= 0) {
29187
+ return fieldFilter.op;
29188
+ }
29189
+ }
29190
+ }
29191
+ return null;
29192
+ }
28483
29193
  function validateNewOrderBy(query, orderBy) {
28484
29194
  if (getFirstOrderByField(query) === null) {
28485
29195
  // This is the first order by. It must match any inequality.
@@ -28497,6 +29207,24 @@ function validateOrderByAndInequalityMatch(baseQuery, inequality, orderBy) {
28497
29207
  `as your first argument to orderBy(), but your first orderBy() ` +
28498
29208
  `is on field '${orderBy.toString()}' instead.`);
28499
29209
  }
29210
+ }
29211
+ function validateQueryFilterConstraint(functionName, queryConstraint) {
29212
+ if (!(queryConstraint instanceof QueryFieldFilterConstraint) &&
29213
+ !(queryConstraint instanceof QueryCompositeFilterConstraint)) {
29214
+ throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);
29215
+ }
29216
+ }
29217
+ function validateQueryConstraintArray(queryConstraint) {
29218
+ const compositeFilterCount = queryConstraint.filter(filter => filter instanceof QueryCompositeFilterConstraint).length;
29219
+ const fieldFilterCount = queryConstraint.filter(filter => filter instanceof QueryFieldFilterConstraint).length;
29220
+ if (compositeFilterCount > 1 ||
29221
+ (compositeFilterCount > 0 && fieldFilterCount > 0)) {
29222
+ throw new FirestoreError(Code.INVALID_ARGUMENT, 'InvalidQuery. When using composite filters, you cannot use ' +
29223
+ 'more than one filter at the top level. Consider nesting the multiple ' +
29224
+ 'filters within an `and(...)` statement. For example: ' +
29225
+ 'change `query(query, where(...), or(...))` to ' +
29226
+ '`query(query, and(where(...), or(...)))`.');
29227
+ }
28500
29228
  }
28501
29229
 
28502
29230
  /**
@@ -29812,9 +30540,15 @@ exports.FirestoreError = FirestoreError;
29812
30540
  exports.GeoPoint = GeoPoint;
29813
30541
  exports.LoadBundleTask = LoadBundleTask;
29814
30542
  exports.Query = Query;
30543
+ exports.QueryCompositeFilterConstraint = QueryCompositeFilterConstraint;
29815
30544
  exports.QueryConstraint = QueryConstraint;
29816
30545
  exports.QueryDocumentSnapshot = QueryDocumentSnapshot;
30546
+ exports.QueryEndAtConstraint = QueryEndAtConstraint;
30547
+ exports.QueryFieldFilterConstraint = QueryFieldFilterConstraint;
30548
+ exports.QueryLimitConstraint = QueryLimitConstraint;
30549
+ exports.QueryOrderByConstraint = QueryOrderByConstraint;
29817
30550
  exports.QuerySnapshot = QuerySnapshot;
30551
+ exports.QueryStartAtConstraint = QueryStartAtConstraint;
29818
30552
  exports.SnapshotMetadata = SnapshotMetadata;
29819
30553
  exports.Timestamp = Timestamp;
29820
30554
  exports.Transaction = Transaction;
@@ -29831,6 +30565,7 @@ exports._logWarn = logWarn;
29831
30565
  exports._validateIsNotUsedTogether = validateIsNotUsedTogether;
29832
30566
  exports.addDoc = addDoc;
29833
30567
  exports.aggregateQuerySnapshotEqual = aggregateQuerySnapshotEqual;
30568
+ exports.and = and;
29834
30569
  exports.arrayRemove = arrayRemove;
29835
30570
  exports.arrayUnion = arrayUnion;
29836
30571
  exports.clearIndexedDbPersistence = clearIndexedDbPersistence;
@@ -29865,6 +30600,7 @@ exports.loadBundle = loadBundle;
29865
30600
  exports.namedQuery = namedQuery;
29866
30601
  exports.onSnapshot = onSnapshot;
29867
30602
  exports.onSnapshotsInSync = onSnapshotsInSync;
30603
+ exports.or = or;
29868
30604
  exports.orderBy = orderBy;
29869
30605
  exports.query = query;
29870
30606
  exports.queryEqual = queryEqual;