@firebase/firestore
Version:
The Cloud Firestore component of the Firebase JS SDK.
1,336 lines (1,315 loc) • 124 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var commonAbf03211 = require('./common-2c6a7547.cjs.js');
require('@firebase/app');
require('@firebase/util');
require('@firebase/webchannel-wrapper/bloom-blob');
require('@firebase/logger');
require('@firebase/webchannel-wrapper/webchannel-blob');
/**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint @typescript-eslint/no-explicit-any: 0 */ function __PRIVATE_isFirestoreValue(t) {
return "object" == typeof t && null !== t && !!("nullValue" in t && (null === t.nullValue || "NULL_VALUE" === t.nullValue) || "booleanValue" in t && (null === t.booleanValue || "boolean" == typeof t.booleanValue) || "integerValue" in t && (null === t.integerValue || "number" == typeof t.integerValue || "string" == typeof t.integerValue) || "doubleValue" in t && (null === t.doubleValue || "number" == typeof t.doubleValue) || "timestampValue" in t && (null === t.timestampValue || function __PRIVATE_isITimestamp(e) {
return "object" == typeof e && null !== e && "seconds" in e && (null === e.seconds || "number" == typeof e.seconds || "string" == typeof e.seconds) && "nanos" in e && (null === e.nanos || "number" == typeof e.nanos);
}(t.timestampValue)) || "stringValue" in t && (null === t.stringValue || "string" == typeof t.stringValue) || "bytesValue" in t && (null === t.bytesValue || t.bytesValue instanceof Uint8Array) || "referenceValue" in t && (null === t.referenceValue || "string" == typeof t.referenceValue) || "geoPointValue" in t && (null === t.geoPointValue || function __PRIVATE_isILatLng(e) {
return "object" == typeof e && null !== e && "latitude" in e && (null === e.latitude || "number" == typeof e.latitude) && "longitude" in e && (null === e.longitude || "number" == typeof e.longitude);
}(t.geoPointValue)) || "arrayValue" in t && (null === t.arrayValue || function __PRIVATE_isIArrayValue(e) {
return "object" == typeof e && null !== e && !(!("values" in e) || null !== e.values && !Array.isArray(e.values));
}(t.arrayValue)) || "mapValue" in t && (null === t.mapValue || function __PRIVATE_isIMapValue(t) {
return "object" == typeof t && null !== t && !(!("fields" in t) || null !== t.fields && !commonAbf03211.__PRIVATE_isPlainObject(t.fields));
}(t.mapValue)) || "fieldReferenceValue" in t && (null === t.fieldReferenceValue || "string" == typeof t.fieldReferenceValue) || "functionValue" in t && (null === t.functionValue || function __PRIVATE_isIFunction(e) {
return "object" == typeof e && null !== e && !(!("name" in e) || null !== e.name && "string" != typeof e.name || !("args" in e) || null !== e.args && !Array.isArray(e.args));
}(t.functionValue)) || "pipelineValue" in t && (null === t.pipelineValue || function __PRIVATE_isIPipeline(e) {
return "object" == typeof e && null !== e && !(!("stages" in e) || null !== e.stages && !Array.isArray(e.stages));
}(t.pipelineValue)));
// Check optional properties and their types
}
/**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Converts a value to an Expression, Returning either a Constant, MapFunction,
* ArrayFunction, or the input itself (if it's already an expression).
*
* @private
* @internal
* @param value
*/ function __PRIVATE_valueToDefaultExpr$1(t) {
let n;
return t instanceof Expression ? t : (n = commonAbf03211.__PRIVATE_isPlainObject(t) ? __PRIVATE__map(t) : t instanceof Array ? array(t) : __PRIVATE__constant(t, void 0),
n);
}
/**
* Converts a value to an Expression, Returning either a Constant, MapFunction,
* ArrayFunction, or the input itself (if it's already an expression).
*
* @private
* @internal
* @param value
*/ function __PRIVATE_vectorToExpr$1(e) {
if (e instanceof Expression) return e;
if (e instanceof commonAbf03211.VectorValue) return constant(e);
if (Array.isArray(e)) return constant(commonAbf03211.vector(e));
throw new Error("Unsupported value: " + typeof e);
}
/**
* Converts a value to an Expression, Returning either a Constant, MapFunction,
* ArrayFunction, or the input itself (if it's already an expression).
* If the input is a string, it is assumed to be a field name, and a
* field(value) is returned.
*
* @private
* @internal
* @param value
*/ function __PRIVATE_fieldOrExpression$1(e) {
if (commonAbf03211.__PRIVATE_isString(e)) {
return field(e);
}
return __PRIVATE_valueToDefaultExpr$1(e);
}
/**
* @beta
*
* Represents an expression that can be evaluated to a value within the execution of a {@link
* @firebase/firestore/pipelines#Pipeline}.
*
* Expressions are the building blocks for creating complex queries and transformations in
* Firestore pipelines. They can represent:
*
* - **Field references:** Access values from document fields.
* - **Literals:** Represent constant values (strings, numbers, booleans).
* - **Function calls:** Apply functions to one or more expressions.
*
* The `Expression` class provides a fluent API for building expressions. You can chain together
* method calls to create complex expressions.
*/ class Expression {
constructor() {
this._protoValueType = "ProtoValue";
}
/**
* Creates an expression that adds this expression to another expression.
*
* @example
* ```typescript
* // Add the value of the 'quantity' field and the 'reserve' field.
* field("quantity").add(field("reserve"));
* ```
*
* @param second - The expression or literal to add to this expression.
* @param others - Optional additional expressions or literals to add to this expression.
* @returns A new `Expression` representing the addition operation.
*/ add(e) {
return new FunctionExpression("add", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "add");
}
/**
* @beta
* Wraps the expression in a [BooleanExpression].
*
* @returns A [BooleanExpression] representing the same expression.
*/ asBoolean() {
if (this instanceof BooleanExpression) return this;
if (this instanceof Constant) return new __PRIVATE_BooleanConstant(this);
if (this instanceof Field) return new __PRIVATE_BooleanField(this);
if (this instanceof FunctionExpression) return new __PRIVATE_BooleanFunctionExpression(this);
throw new commonAbf03211.FirestoreError("invalid-argument", `Conversion of type ${typeof this} to BooleanExpression not supported.`);
}
subtract(e) {
return new FunctionExpression("subtract", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "subtract");
}
/**
* @beta
* Creates an expression that multiplies this expression by another expression.
*
* @example
* ```typescript
* // Multiply the 'quantity' field by the 'price' field
* field("quantity").multiply(field("price"));
* ```
*
* @param second - The second expression or literal to multiply by.
* @param others - Optional additional expressions or literals to multiply by.
* @returns A new `Expression` representing the multiplication operation.
*/ multiply(e) {
return new FunctionExpression("multiply", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "multiply");
}
divide(e) {
return new FunctionExpression("divide", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "divide");
}
mod(e) {
return new FunctionExpression("mod", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "mod");
}
equal(e) {
return new FunctionExpression("equal", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "equal").asBoolean();
}
notEqual(e) {
return new FunctionExpression("not_equal", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "notEqual").asBoolean();
}
lessThan(e) {
return new FunctionExpression("less_than", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "lessThan").asBoolean();
}
lessThanOrEqual(e) {
return new FunctionExpression("less_than_or_equal", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "lessThanOrEqual").asBoolean();
}
greaterThan(e) {
return new FunctionExpression("greater_than", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "greaterThan").asBoolean();
}
greaterThanOrEqual(e) {
return new FunctionExpression("greater_than_or_equal", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "greaterThanOrEqual").asBoolean();
}
/**
* @beta
* Creates an expression that concatenates an array expression with one or more other arrays.
*
* @example
* ```typescript
* // Combine the 'items' array with another array field.
* field("items").arrayConcat(field("otherItems"));
* ```
* @param secondArray - Second array expression or array literal to concatenate.
* @param otherArrays - Optional additional array expressions or array literals to concatenate.
* @returns A new `Expression` representing the concatenated array.
*/ arrayConcat(e, ...t) {
const n = [ e, ...t ].map((e => __PRIVATE_valueToDefaultExpr$1(e)));
return new FunctionExpression("array_concat", [ this, ...n ], "arrayConcat");
}
arrayContains(e) {
return new FunctionExpression("array_contains", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "arrayContains").asBoolean();
}
arrayContainsAll(e) {
const t = Array.isArray(e) ? new __PRIVATE_ListOfExprs(e.map(__PRIVATE_valueToDefaultExpr$1), "arrayContainsAll") : e;
return new FunctionExpression("array_contains_all", [ this, t ], "arrayContainsAll").asBoolean();
}
arrayContainsAny(e) {
const t = Array.isArray(e) ? new __PRIVATE_ListOfExprs(e.map(__PRIVATE_valueToDefaultExpr$1), "arrayContainsAny") : e;
return new FunctionExpression("array_contains_any", [ this, t ], "arrayContainsAny").asBoolean();
}
/**
* @beta
* Creates an expression that reverses an array.
*
* @example
* ```typescript
* // Reverse the value of the 'myArray' field.
* field("myArray").arrayReverse();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed array.
*/ arrayReverse() {
return new FunctionExpression("array_reverse", [ this ]);
}
/**
* @beta
* Creates an expression that calculates the length of an array.
*
* @example
* ```typescript
* // Get the number of items in the 'cart' array
* field("cart").arrayLength();
* ```
*
* @returns A new `Expression` representing the length of the array.
*/ arrayLength() {
return new FunctionExpression("array_length", [ this ], "arrayLength");
}
equalAny(e) {
const t = Array.isArray(e) ? new __PRIVATE_ListOfExprs(e.map(__PRIVATE_valueToDefaultExpr$1), "equalAny") : e;
return new FunctionExpression("equal_any", [ this, t ], "equalAny").asBoolean();
}
notEqualAny(e) {
const t = Array.isArray(e) ? new __PRIVATE_ListOfExprs(e.map(__PRIVATE_valueToDefaultExpr$1), "notEqualAny") : e;
return new FunctionExpression("not_equal_any", [ this, t ], "notEqualAny").asBoolean();
}
/**
* @beta
* Creates an expression that checks if a field exists in the document.
*
* @example
* ```typescript
* // Check if the document has a field named "phoneNumber"
* field("phoneNumber").exists();
* ```
*
* @returns A new `Expression` representing the 'exists' check.
*/ exists() {
return new FunctionExpression("exists", [ this ], "exists").asBoolean();
}
/**
* @beta
* Creates an expression that calculates the character length of a string in UTF-8.
*
* @example
* ```typescript
* // Get the character length of the 'name' field in its UTF-8 form.
* field("name").charLength();
* ```
*
* @returns A new `Expression` representing the length of the string.
*/ charLength() {
return new FunctionExpression("char_length", [ this ], "charLength");
}
like(e) {
return new FunctionExpression("like", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "like").asBoolean();
}
regexContains(e) {
return new FunctionExpression("regex_contains", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "regexContains").asBoolean();
}
regexMatch(e) {
return new FunctionExpression("regex_match", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "regexMatch").asBoolean();
}
stringContains(e) {
return new FunctionExpression("string_contains", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "stringContains").asBoolean();
}
startsWith(e) {
return new FunctionExpression("starts_with", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "startsWith").asBoolean();
}
endsWith(e) {
return new FunctionExpression("ends_with", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "endsWith").asBoolean();
}
/**
* @beta
* Creates an expression that converts a string to lowercase.
*
* @example
* ```typescript
* // Convert the 'name' field to lowercase
* field("name").toLower();
* ```
*
* @returns A new `Expression` representing the lowercase string.
*/ toLower() {
return new FunctionExpression("to_lower", [ this ], "toLower");
}
/**
* @beta
* Creates an expression that converts a string to uppercase.
*
* @example
* ```typescript
* // Convert the 'title' field to uppercase
* field("title").toUpper();
* ```
*
* @returns A new `Expression` representing the uppercase string.
*/ toUpper() {
return new FunctionExpression("to_upper", [ this ], "toUpper");
}
/**
* @beta
* Creates an expression that removes leading and trailing characters from a string or byte array.
*
* @example
* ```typescript
* // Trim whitespace from the 'userInput' field
* field("userInput").trim();
*
* // Trim quotes from the 'userInput' field
* field("userInput").trim('"');
* ```
* @param valueToTrim - Optional This parameter is treated as a set of characters or bytes that will be
* trimmed from the input. If not specified, then whitespace will be trimmed.
* @returns A new `Expression` representing the trimmed string or byte array.
*/ trim(e) {
const t = [ this ];
return e && t.push(__PRIVATE_valueToDefaultExpr$1(e)), new FunctionExpression("trim", t, "trim");
}
/**
* @beta
* Creates an expression that concatenates string expressions together.
*
* @example
* ```typescript
* // Combine the 'firstName', " ", and 'lastName' fields into a single string
* field("firstName").stringConcat(constant(" "), field("lastName"));
* ```
*
* @param secondString - The additional expression or string literal to concatenate.
* @param otherStrings - Optional additional expressions or string literals to concatenate.
* @returns A new `Expression` representing the concatenated string.
*/ stringConcat(e, ...t) {
const n = [ e, ...t ].map(__PRIVATE_valueToDefaultExpr$1);
return new FunctionExpression("string_concat", [ this, ...n ], "stringConcat");
}
/**
* @beta
* Creates an expression that concatenates expression results together.
*
* @example
* ```typescript
* // Combine the 'firstName', ' ', and 'lastName' fields into a single value.
* field("firstName").concat(constant(" "), field("lastName"));
* ```
*
* @param second - The additional expression or literal to concatenate.
* @param others - Optional additional expressions or literals to concatenate.
* @returns A new `Expression` representing the concatenated value.
*/ concat(e, ...t) {
const n = [ e, ...t ].map(__PRIVATE_valueToDefaultExpr$1);
return new FunctionExpression("concat", [ this, ...n ], "concat");
}
/**
* @beta
* Creates an expression that reverses this string expression.
*
* @example
* ```typescript
* // Reverse the value of the 'myString' field.
* field("myString").reverse();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.
*/ reverse() {
return new FunctionExpression("reverse", [ this ], "reverse");
}
/**
* @beta
* Creates an expression that calculates the length of this string expression in bytes.
*
* @example
* ```typescript
* // Calculate the length of the 'myString' field in bytes.
* field("myString").byteLength();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string in bytes.
*/ byteLength() {
return new FunctionExpression("byte_length", [ this ], "byteLength");
}
/**
* @beta
* Creates an expression that computes the ceiling of a numeric value.
*
* @example
* ```typescript
* // Compute the ceiling of the 'price' field.
* field("price").ceil();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ceiling of the numeric value.
*/ ceil() {
return new FunctionExpression("ceil", [ this ]);
}
/**
* @beta
* Creates an expression that computes the floor of a numeric value.
*
* @example
* ```typescript
* // Compute the floor of the 'price' field.
* field("price").floor();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the floor of the numeric value.
*/ floor() {
return new FunctionExpression("floor", [ this ]);
}
/**
* @beta
* Creates an expression that computes the absolute value of a numeric value.
*
* @example
* ```typescript
* // Compute the absolute value of the 'price' field.
* field("price").abs();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the absolute value of the numeric value.
*/ abs() {
return new FunctionExpression("abs", [ this ]);
}
/**
* @beta
* Creates an expression that computes e to the power of this expression.
*
* @example
* ```typescript
* // Compute e to the power of the 'value' field.
* field("value").exp();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the exp of the numeric value.
*/ exp() {
return new FunctionExpression("exp", [ this ]);
}
/**
* @beta
* Accesses a value from a map (object) field using the provided key.
*
* @example
* ```typescript
* // Get the 'city' value from the 'address' map field
* field("address").mapGet("city");
* ```
*
* @param subfield - The key to access in the map.
* @returns A new `Expression` representing the value associated with the given key in the map.
*/ mapGet(e) {
return new FunctionExpression("map_get", [ this, constant(e) ], "mapGet");
}
/**
* @beta
* Creates an aggregation that counts the number of stage inputs with valid evaluations of the
* expression or field.
*
* @example
* ```typescript
* // Count the total number of products
* field("productId").count().as("totalProducts");
* ```
*
* @returns A new `AggregateFunction` representing the 'count' aggregation.
*/ count() {
return AggregateFunction._create("count", [ this ], "count");
}
/**
* @beta
* Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs.
*
* @example
* ```typescript
* // Calculate the total revenue from a set of orders
* field("orderAmount").sum().as("totalRevenue");
* ```
*
* @returns A new `AggregateFunction` representing the 'sum' aggregation.
*/ sum() {
return AggregateFunction._create("sum", [ this ], "sum");
}
/**
* @beta
* Creates an aggregation that calculates the average (mean) of a numeric field across multiple
* stage inputs.
*
* @example
* ```typescript
* // Calculate the average age of users
* field("age").average().as("averageAge");
* ```
*
* @returns A new `AggregateFunction` representing the 'average' aggregation.
*/ average() {
return AggregateFunction._create("average", [ this ], "average");
}
/**
* @beta
* Creates an aggregation that finds the minimum value of a field across multiple stage inputs.
*
* @example
* ```typescript
* // Find the lowest price of all products
* field("price").minimum().as("lowestPrice");
* ```
*
* @returns A new `AggregateFunction` representing the 'minimum' aggregation.
*/ minimum() {
return AggregateFunction._create("minimum", [ this ], "minimum");
}
/**
* @beta
* Creates an aggregation that finds the maximum value of a field across multiple stage inputs.
*
* @example
* ```typescript
* // Find the highest score in a leaderboard
* field("score").maximum().as("highestScore");
* ```
*
* @returns A new `AggregateFunction` representing the 'maximum' aggregation.
*/ maximum() {
return AggregateFunction._create("maximum", [ this ], "maximum");
}
/**
* @beta
* Creates an aggregation that counts the number of distinct values of the expression or field.
*
* @example
* ```typescript
* // Count the distinct number of products
* field("productId").countDistinct().as("distinctProducts");
* ```
*
* @returns A new `AggregateFunction` representing the 'count_distinct' aggregation.
*/ countDistinct() {
return AggregateFunction._create("count_distinct", [ this ], "countDistinct");
}
/**
* @beta
* Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering.
*
* @example
* ```typescript
* // Returns the larger value between the 'timestamp' field and the current timestamp.
* field("timestamp").logicalMaximum(Function.currentTimestamp());
* ```
*
* @param second - The second expression or literal to compare with.
* @param others - Optional additional expressions or literals to compare with.
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical maximum operation.
*/ logicalMaximum(e, ...t) {
const n = [ e, ...t ];
return new FunctionExpression("maximum", [ this, ...n.map(__PRIVATE_valueToDefaultExpr$1) ], "logicalMaximum");
}
/**
* @beta
* Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering.
*
* @example
* ```typescript
* // Returns the smaller value between the 'timestamp' field and the current timestamp.
* field("timestamp").logicalMinimum(Function.currentTimestamp());
* ```
*
* @param second - The second expression or literal to compare with.
* @param others - Optional additional expressions or literals to compare with.
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical minimum operation.
*/ logicalMinimum(e, ...t) {
const n = [ e, ...t ];
return new FunctionExpression("minimum", [ this, ...n.map(__PRIVATE_valueToDefaultExpr$1) ], "minimum");
}
/**
* @beta
* Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression.
*
* @example
* ```typescript
* // Get the vector length (dimension) of the field 'embedding'.
* field("embedding").vectorLength();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the vector.
*/ vectorLength() {
return new FunctionExpression("vector_length", [ this ], "vectorLength");
}
cosineDistance(e) {
return new FunctionExpression("cosine_distance", [ this, __PRIVATE_vectorToExpr$1(e) ], "cosineDistance");
}
dotProduct(e) {
return new FunctionExpression("dot_product", [ this, __PRIVATE_vectorToExpr$1(e) ], "dotProduct");
}
euclideanDistance(e) {
return new FunctionExpression("euclidean_distance", [ this, __PRIVATE_vectorToExpr$1(e) ], "euclideanDistance");
}
/**
* @beta
* Creates an expression that interprets this expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC)
* and returns a timestamp.
*
* @example
* ```typescript
* // Interpret the 'microseconds' field as microseconds since epoch.
* field("microseconds").unixMicrosToTimestamp();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.
*/ unixMicrosToTimestamp() {
return new FunctionExpression("unix_micros_to_timestamp", [ this ], "unixMicrosToTimestamp");
}
/**
* @beta
* Creates an expression that converts this timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC).
*
* @example
* ```typescript
* // Convert the 'timestamp' field to microseconds since epoch.
* field("timestamp").timestampToUnixMicros();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of microseconds since epoch.
*/ timestampToUnixMicros() {
return new FunctionExpression("timestamp_to_unix_micros", [ this ], "timestampToUnixMicros");
}
/**
* @beta
* Creates an expression that interprets this expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC)
* and returns a timestamp.
*
* @example
* ```typescript
* // Interpret the 'milliseconds' field as milliseconds since epoch.
* field("milliseconds").unixMillisToTimestamp();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.
*/ unixMillisToTimestamp() {
return new FunctionExpression("unix_millis_to_timestamp", [ this ], "unixMillisToTimestamp");
}
/**
* @beta
* Creates an expression that converts this timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC).
*
* @example
* ```typescript
* // Convert the 'timestamp' field to milliseconds since epoch.
* field("timestamp").timestampToUnixMillis();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of milliseconds since epoch.
*/ timestampToUnixMillis() {
return new FunctionExpression("timestamp_to_unix_millis", [ this ], "timestampToUnixMillis");
}
/**
* @beta
* Creates an expression that interprets this expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC)
* and returns a timestamp.
*
* @example
* ```typescript
* // Interpret the 'seconds' field as seconds since epoch.
* field("seconds").unixSecondsToTimestamp();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.
*/ unixSecondsToTimestamp() {
return new FunctionExpression("unix_seconds_to_timestamp", [ this ], "unixSecondsToTimestamp");
}
/**
* @beta
* Creates an expression that converts this timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).
*
* @example
* ```typescript
* // Convert the 'timestamp' field to seconds since epoch.
* field("timestamp").timestampToUnixSeconds();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of seconds since epoch.
*/ timestampToUnixSeconds() {
return new FunctionExpression("timestamp_to_unix_seconds", [ this ], "timestampToUnixSeconds");
}
timestampAdd(e, t) {
return new FunctionExpression("timestamp_add", [ this, __PRIVATE_valueToDefaultExpr$1(e), __PRIVATE_valueToDefaultExpr$1(t) ], "timestampAdd");
}
timestampSubtract(e, t) {
return new FunctionExpression("timestamp_subtract", [ this, __PRIVATE_valueToDefaultExpr$1(e), __PRIVATE_valueToDefaultExpr$1(t) ], "timestampSubtract");
}
/**
* @beta
*
* Creates an expression that returns the document ID from a path.
*
* @example
* ```typescript
* // Get the document ID from a path.
* field("__path__").documentId();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the documentId operation.
*/ documentId() {
return new FunctionExpression("document_id", [ this ], "documentId");
}
substring(e, t) {
const n = __PRIVATE_valueToDefaultExpr$1(e);
return new FunctionExpression("substring", void 0 === t ? [ this, n ] : [ this, n, __PRIVATE_valueToDefaultExpr$1(t) ], "substring");
}
arrayGet(e) {
return new FunctionExpression("array_get", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "arrayGet");
}
/**
* @beta
*
* Creates an expression that checks if a given expression produces an error.
*
* @example
* ```typescript
* // Check if the result of a calculation is an error
* field("title").arrayContains(1).isError();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#BooleanExpression} representing the 'isError' check.
*/ isError() {
return new FunctionExpression("is_error", [ this ], "isError").asBoolean();
}
ifError(e) {
const t = new FunctionExpression("if_error", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "ifError");
return e instanceof BooleanExpression ? t.asBoolean() : t;
}
/**
* @beta
*
* Creates an expression that returns `true` if the result of this expression
* is absent. Otherwise, returns `false` even if the value is `null`.
*
* @example
* ```typescript
* // Check if the field `value` is absent.
* field("value").isAbsent();
* @example
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#BooleanExpression} representing the 'isAbsent' check.
*/ isAbsent() {
return new FunctionExpression("is_absent", [ this ], "isAbsent").asBoolean();
}
mapRemove(e) {
return new FunctionExpression("map_remove", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "mapRemove");
}
/**
* @beta
*
* Creates an expression that merges multiple map values.
*
* @example
* ```
* // Merges the map in the settings field with, a map literal, and a map in
* // that is conditionally returned by another expression
* field('settings').mapMerge({ enabled: true }, conditional(field('isAdmin'), { admin: true}, {})
* ```
*
* @param secondMap - A required second map to merge. Represented as a literal or
* an expression that returns a map.
* @param otherMaps - Optional additional maps to merge. Each map is represented
* as a literal or an expression that returns a map.
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'mapMerge' operation.
*/ mapMerge(e, ...t) {
const n = __PRIVATE_valueToDefaultExpr$1(e), r = t.map(__PRIVATE_valueToDefaultExpr$1);
return new FunctionExpression("map_merge", [ this, n, ...r ], "mapMerge");
}
pow(e) {
return new FunctionExpression("pow", [ this, __PRIVATE_valueToDefaultExpr$1(e) ]);
}
round(e) {
return void 0 === e ? new FunctionExpression("round", [ this ]) : new FunctionExpression("round", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "round");
}
/**
* @beta
* Creates an expression that returns the collection ID from a path.
*
* @example
* ```typescript
* // Get the collection ID from a path.
* field("__path__").collectionId();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the collectionId operation.
*/ collectionId() {
return new FunctionExpression("collection_id", [ this ]);
}
/**
* @beta
* Creates an expression that calculates the length of a string, array, map, vector, or bytes.
*
* @example
* ```typescript
* // Get the length of the 'name' field.
* field("name").length();
*
* // Get the number of items in the 'cart' array.
* field("cart").length();
* ```
*
* @returns A new `Expression` representing the length of the string, array, map, vector, or bytes.
*/ length() {
return new FunctionExpression("length", [ this ]);
}
/**
* @beta
* Creates an expression that computes the natural logarithm of a numeric value.
*
* @example
* ```typescript
* // Compute the natural logarithm of the 'value' field.
* field("value").ln();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the natural logarithm of the numeric value.
*/ ln() {
return new FunctionExpression("ln", [ this ]);
}
/**
* @beta
* Creates an expression that computes the square root of a numeric value.
*
* @example
* ```typescript
* // Compute the square root of the 'value' field.
* field("value").sqrt();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the square root of the numeric value.
*/ sqrt() {
return new FunctionExpression("sqrt", [ this ]);
}
/**
* @beta
* Creates an expression that reverses a string.
*
* @example
* ```typescript
* // Reverse the value of the 'myString' field.
* field("myString").stringReverse();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.
*/ stringReverse() {
return new FunctionExpression("string_reverse", [ this ]);
}
ifAbsent(e) {
return new FunctionExpression("if_absent", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "ifAbsent");
}
join(e) {
return new FunctionExpression("join", [ this, __PRIVATE_valueToDefaultExpr$1(e) ], "join");
}
/**
* @beta
* Creates an expression that computes the base-10 logarithm of a numeric value.
*
* @example
* ```typescript
* // Compute the base-10 logarithm of the 'value' field.
* field("value").log10();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the base-10 logarithm of the numeric value.
*/ log10() {
return new FunctionExpression("log10", [ this ]);
}
/**
* @beta
* Creates an expression that computes the sum of the elements in an array.
*
* @example
* ```typescript
* // Compute the sum of the elements in the 'scores' field.
* field("scores").arraySum();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the sum of the elements in the array.
*/ arraySum() {
return new FunctionExpression("sum", [ this ]);
}
split(e) {
return new FunctionExpression("split", [ this, __PRIVATE_valueToDefaultExpr$1(e) ]);
}
timestampTruncate(e, t) {
const r = [ this, __PRIVATE_valueToDefaultExpr$1(commonAbf03211.__PRIVATE_isString(e) ? e.toLowerCase() : e) ];
return t && r.push(__PRIVATE_valueToDefaultExpr$1(t)), new FunctionExpression("timestamp_trunc", r);
}
/**
* @beta
* Creates an expression that returns the data type of this expression's result, as a string.
*
* @example
* ```typescript
* // Get the data type of the value in field 'title'
* field('title').type()
* ```
*
* @returns A new `Expression` representing the data type.
*/ type() {
return new FunctionExpression("type", [ this ]);
}
// TODO(new-expression): Add new expression method definitions above this line
/**
* @beta
* Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in ascending order based on this expression.
*
* @example
* ```typescript
* // Sort documents by the 'name' field in ascending order
* pipeline().collection("users")
* .sort(field("name").ascending());
* ```
*
* @returns A new `Ordering` for ascending sorting.
*/
ascending() {
return ascending(this);
}
/**
* @beta
* Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in descending order based on this expression.
*
* @example
* ```typescript
* // Sort documents by the 'createdAt' field in descending order
* firestore.pipeline().collection("users")
* .sort(field("createdAt").descending());
* ```
*
* @returns A new `Ordering` for descending sorting.
*/ descending() {
return descending(this);
}
/**
* @beta
* Assigns an alias to this expression.
*
* Aliases are useful for renaming fields in the output of a stage or for giving meaningful
* names to calculated values.
*
* @example
* ```typescript
* // Calculate the total price and assign it the alias "totalPrice" and add it to the output.
* firestore.pipeline().collection("items")
* .addFields(field("price").multiply(field("quantity")).as("totalPrice"));
* ```
*
* @param name - The alias to assign to this expression.
* @returns A new {@link @firebase/firestore/pipelines#AliasedExpression} that wraps this
* expression and associates it with the provided alias.
*/ as(e) {
return new AliasedExpression(this, e, "as");
}
}
/**
* @beta
*
* A class that represents an aggregate function.
*/ class AggregateFunction {
constructor(e, t) {
this.name = e, this.params = t, this.exprType = "AggregateFunction", this._protoValueType = "ProtoValue";
}
/**
* @internal
* @private
*/ static _create(e, t, n) {
const r = new AggregateFunction(e, t);
return r._methodName = n, r;
}
/**
* @beta
* Assigns an alias to this AggregateFunction. The alias specifies the name that
* the aggregated value will have in the output document.
*
* @example
* ```typescript
* // Calculate the average price of all items and assign it the alias "averagePrice".
* firestore.pipeline().collection("items")
* .aggregate(field("price").average().as("averagePrice"));
* ```
*
* @param name - The alias to assign to this AggregateFunction.
* @returns A new {@link @firebase/firestore/pipelines#AliasedAggregate} that wraps this
* AggregateFunction and associates it with the provided alias.
*/ as(e) {
return new AliasedAggregate(this, e, "as");
}
/**
* @private
* @internal
*/ _toProto(e) {
return {
functionValue: {
name: this.name,
args: this.params.map((t => t._toProto(e)))
}
};
}
/**
* @private
* @internal
*/ _readUserData(e) {
e = this._methodName ? e.contextWith({
methodName: this._methodName
}) : e, this.params.forEach((t => t._readUserData(e)));
}
}
/**
* @beta
*
* An AggregateFunction with alias.
*/ class AliasedAggregate {
constructor(e, t, n) {
this.aggregate = e, this.alias = t, this._methodName = n;
}
/**
* @private
* @internal
*/ _readUserData(e) {
this.aggregate._readUserData(e);
}
}
/**
* @beta
*/ class AliasedExpression {
constructor(e, t, n) {
this.expr = e, this.alias = t, this._methodName = n, this.exprType = "AliasedExpression",
this.selectable = !0;
}
/**
* @private
* @internal
*/ _readUserData(e) {
this.expr._readUserData(e);
}
}
/**
* @internal
*/ class __PRIVATE_ListOfExprs extends Expression {
constructor(e, t) {
super(), this.t = e, this._methodName = t, this.expressionType = "ListOfExpressions";
}
/**
* @private
* @internal
*/ _toProto(e) {
return {
arrayValue: {
values: this.t.map((t => t._toProto(e)))
}
};
}
/**
* @private
* @internal
*/ _readUserData(e) {
this.t.forEach((t => t._readUserData(e)));
}
}
/**
* @beta
*
* Represents a reference to a field in a Firestore document, or outputs of a {@link @firebase/firestore/pipelines#Pipeline} stage.
*
* <p>Field references are used to access document field values in expressions and to specify fields
* for sorting, filtering, and projecting data in Firestore pipelines.
*
* <p>You can create a `Field` instance using the static {@link @firebase/firestore/pipelines#field} method:
*
* @example
* ```typescript
* // Create a Field instance for the 'name' field
* const nameField = field("name");
*
* // Create a Field instance for a nested field 'address.city'
* const cityField = field("address.city");
* ```
*/ class Field extends Expression {
/**
* @internal
* @private
* @hideconstructor
* @param fieldPath
*/
constructor(e, t) {
super(), this.fieldPath = e, this._methodName = t, this.expressionType = "Field",
this.selectable = !0;
}
get fieldName() {
return this.fieldPath.canonicalString();
}
get alias() {
return this.fieldName;
}
get expr() {
return this;
}
/**
* @private
* @internal
*/ _toProto(e) {
return {
fieldReferenceValue: this.fieldPath.canonicalString()
};
}
/**
* @private
* @internal
*/ _readUserData(e) {}
}
function field(e) {
return _field(e, "field");
}
function _field(e, t) {
return new Field("string" == typeof e ? commonAbf03211.M === e ? commonAbf03211.documentId()._internalPath : commonAbf03211.__PRIVATE_fieldPathFromArgument("field", e) : e._internalPath, t);
}
/**
* @internal
*
* Represents a constant value that can be used in a Firestore pipeline expression.
*
* You can create a `Constant` instance using the static {@link @firebase/firestore/pipelines#field} method:
*
* @example
* ```typescript
* // Create a Constant instance for the number 10
* const ten = constant(10);
*
* // Create a Constant instance for the string "hello"
* const hello = constant("hello");
* ```
*/ class Constant extends Expression {
/**
* @private
* @internal
* @hideconstructor
* @param value - The value of the constant.
*/
constructor(e, t) {
super(), this.value = e, this._methodName = t, this.expressionType = "Constant";
}
/**
* @private
* @internal
*/ static _fromProto(e) {
const t = new Constant(e, void 0);
return t._protoValue = e, t;
}
/**
* @private
* @internal
*/ _toProto(e) {
return commonAbf03211.__PRIVATE_hardAssert(void 0 !== this._protoValue, 237), this._protoValue;
}
/**
* @private
* @internal
*/ _readUserData(e) {
e = this._methodName ? e.contextWith({
methodName: this._methodName
}) : e, __PRIVATE_isFirestoreValue(this._protoValue) || (this._protoValue = commonAbf03211.__PRIVATE_parseData(this.value, e));
}
}
function constant(e) {
return __PRIVATE__constant(e, "constant");
}
/**
* @internal
* @private
* @param value
* @param methodName
*/ function __PRIVATE__constant(e, t) {
const n = new Constant(e, t);
return "boolean" == typeof e ? new __PRIVATE_BooleanConstant(n) : n;
}
/**
* Internal only
* @internal
* @private
*/ class MapValue extends Expression {
constructor(e, t) {
super(), this.i = e, this._methodName = t, this.expressionType = "Constant";
}
_readUserData(e) {
e = this._methodName ? e.contextWith({
methodName: this._methodName
}) : e, this.i.forEach((t => {
t._readUserData(e);
}));
}
_toProto(e) {
return commonAbf03211.__PRIVATE_toMapValue(e, this.i);
}
}
/**
* @beta
*
* This class defines the base class for Firestore {@link @firebase/firestore/pipelines#Pipeline} functions, which can be evaluated within pipeline
* execution.
*
* Typically, you would not use this class or its children directly. Use either the functions like {@link @firebase/firestore/pipelines#and}, {@link @firebase/firestore/pipelines#(equal:1)},
* or the methods on {@link @firebase/firestore/pipelines#Expression} ({@link @firebase/firestore/pipelines#Expression.(equal:1)}, {@link @firebase/firestore/pipelines#Expression.(lessThan:1)}, etc.) to construct new Function instances.
*/ class FunctionExpression extends Expression {
constructor(e, t, n) {
super(), this.name = e, this.params = t, this._methodName = n, this.expressionType = "Function";
}
/**
* @private
* @internal
*/ _toProto(e) {
return {
functionValue: {
name: this.name,
args: this.params.map((t => t._toProto(e)))
}
};
}
/**
* @private
* @internal
*/ _readUserData(e) {
e = this._methodName ? e.contextWith({
methodName: this._methodName
}) : e, this.params.forEach((t => t._readUserData(e)));
}
}
/**
* @beta
*
* An interface that represents a filter condition.
*/ class BooleanExpression extends Expression {
get _methodName() {
return this._expr._methodName;
}
/**
* @beta
* Creates an aggregation that finds the count of input documents satisfying
* this boolean expression.
*
* @example
* ```typescript
* // Find the count of documents with a score greater than 90
* field("score").greaterThan(90).countIf().as("highestScore");
* ```
*
* @returns A new `AggregateFunction` representing the 'countIf' aggregation.
*/ countIf() {
return AggregateFunction._create("count_if", [ this ], "countIf");
}
/**
* @beta
* Creates an expression that negates this boolean expression.
*
* @example
* ```typescript
* // Find documents where the 'tags' field does not contain 'completed'
* field("tags").arrayContains("completed").not();
* ```
*
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the negated filter condition.
*/ not() {
return new FunctionExpression("not", [ this ], "not").asBoolean();
}
/**
* @beta
* Creates a conditional expression that evaluates to the 'then' expression
* if `this` expression evaluates to `true`,
* or evaluates to the 'else' expression if `this` expressions evaluates `false`.
*
* @example
* ```typescript
* // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor".
* field("age").greaterThanOrEqual(18).conditional(constant("Adult"), constant("Minor"));
* ```
*
* @param thenExpr - The expression to evaluate if the condition is true.
* @param elseExpr - The expression to evaluate if the condition is false.
* @returns A new {@link @firebase/firestore/pipelines#Expression} representing the conditional expression.
*/ conditional(e, t) {
return new FunctionExpression("conditional", [ this, e, t ], "conditional");
}
ifError(e) {
const t = __PRIVATE_valueToDefaultExpr$1(e), n = new FunctionExpression("if_error", [ this, t ], "ifError");
return t instanceof BooleanExpression ? n.asBoolean() : n;
}
/**
* @private
* @internal
*/ _toProto(e) {